<template>
  <div class="ansible-audit-container">
    <!-- 星空背景 -->
    <div class="starry-background">
      <div class="stars"></div>
      <div class="stars2"></div>
      <div class="stars3"></div>
    </div>

    <div class="content-wrapper">
      <!-- 页面标题 -->
      <div class="page-header glass-effect">
        <div class="header-content">
          <div class="title-section">
            <h1><i class="fa fa-desktop"></i> 主机监控</h1>
            <p>查看和管理主机监控状态</p>
          </div>
          <div class="control-section">
            <!-- Zabbix服务器选择器 -->
            <div class="zabbix-selector">
              <label class="selector-label">
                <i class="fa fa-server"></i>
                Zabbix服务器:
              </label>
              <el-select
                v-model="selectedZabbixServer"
                @change="onZabbixServerChange"
                placeholder="请选择Zabbix服务器"
                class="glass-select"
                size="default"
                style="width: 280px;"
              >
                <el-option
                  v-for="server in zabbixServers"
                  :key="server.id"
                  :label="`${server.name} (${server.url})`"
                  :value="server.id"
                >
                  <div class="server-option">
                    <div class="server-name">{{ server.name }}</div>
                    <div class="server-url">{{ server.url }}</div>
                  </div>
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="action-section">
            <!-- 1. 数据刷新按钮 -->
            <el-button
              @click="refreshData"
              class="glass-button refresh-button"
              :loading="loading.refresh"
              :disabled="!selectedZabbixServer"
              type="primary"
            >
              <i class="fa fa-refresh"></i>
              刷新数据
            </el-button>

            <!-- 2. 智能同步下拉按钮 -->
            <el-dropdown @command="handleSyncCommand" :disabled="!selectedZabbixServer" class="sync-dropdown">
              <el-button class="glass-button sync-button" :loading="loading.sync">
                <i class="fa fa-sync"></i>
                智能同步
                <i class="fa fa-caret-down"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu class="glass-dropdown">
                  <el-dropdown-item command="auto">
                    <i class="fa fa-magic"></i>
                    自动同步（推荐）
                  </el-dropdown-item>
                  <el-dropdown-item command="force">
                    <i class="fa fa-redo"></i>
                    强制重新关联
                  </el-dropdown-item>
                  <el-dropdown-item command="cmdb-to-zabbix">
                    <i class="fa fa-arrow-right"></i>
                    CMDB → Zabbix
                  </el-dropdown-item>
                  <el-dropdown-item command="cleanup">
                    <i class="fa fa-broom"></i>
                    清理孤立数据
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 3. 显示设置下拉按钮 -->
            <el-dropdown @command="handleDisplayCommand" class="display-dropdown">
              <el-button class="glass-button display-button">
                <i class="fa fa-cog"></i>
                显示设置
                <i class="fa fa-caret-down"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu class="glass-dropdown">
                  <el-dropdown-item command="show-all">
                    <i class="fa fa-eye"></i>
                    显示全部主机
                  </el-dropdown-item>
                  <el-dropdown-item command="show-linked">
                    <i class="fa fa-link"></i>
                    仅显示已关联
                  </el-dropdown-item>
                  <el-dropdown-item command="show-unlinked">
                    <i class="fa fa-unlink"></i>
                    仅显示未关联
                  </el-dropdown-item>
                  <el-dropdown-item divided command="auto-refresh">
                    <i class="fa fa-clock-o"></i>
                    自动刷新设置
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 4. 主机管理按钮 -->
            <el-button
              @click="showHostManagement"
              class="glass-button management-button"
              :disabled="!selectedZabbixServer"
            >
              <i class="fa fa-plus"></i>
              主机管理
            </el-button>

            <!-- 5. 调试数据按钮（开发用） -->
            <el-button @click="debugData" class="glass-button debug-button" v-if="isDevelopment">
              <i class="fa fa-bug"></i>
              调试数据
            </el-button>
          </div>
        </div>
      </div>

      <!-- 统计卡片 -->
      <div class="stats-grid">
        <div class="stat-card glass-effect">
          <div class="stat-icon">
            <i class="fa fa-server"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.total_hosts || 0 }}</div>
            <div class="stat-label">监控主机</div>
          </div>
        </div>

        <div class="stat-card glass-effect">
          <div class="stat-icon online">
            <i class="fa fa-check-circle"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.online_hosts || 0 }}</div>
            <div class="stat-label">在线主机</div>
          </div>
        </div>

        <div class="stat-card glass-effect">
          <div class="stat-icon offline">
            <i class="fa fa-times-circle"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.offline_hosts || 0 }}</div>
            <div class="stat-label">离线主机</div>
          </div>
        </div>

        <div class="stat-card glass-effect">
          <div class="stat-icon warning">
            <i class="fa fa-exclamation-triangle"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.alert_hosts || 0 }}</div>
            <div class="stat-label">告警主机</div>
          </div>
        </div>
      </div>

      <!-- 主机列表 -->
      <div class="hosts-section glass-effect">
        <div class="section-header">
          <h3><i class="fa fa-list"></i> 主机列表</h3>
          <div class="filter-controls">
            <div class="collapse-controls">
              <button @click="expandAllSections" class="glass-button expand-button">
                <i class="fa fa-expand-arrows-alt"></i>
                全部展开
              </button>
              <button @click="collapseAllSections" class="glass-button collapse-button">
                <i class="fa fa-compress-arrows-alt"></i>
                全部折叠
              </button>
            </div>
            <el-select v-model="filterStatus" placeholder="状态筛选" style="width: 120px;">
              <el-option label="全部" value="" />
              <el-option label="在线" value="online" />
              <el-option label="离线" value="offline" />
              <el-option label="未知" value="unknown" />
            </el-select>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索主机名或IP"
              style="width: 200px;"
              clearable
            >
              <template #prefix>
                <i class="fa fa-search"></i>
              </template>
            </el-input>
          </div>
        </div>

        <!-- 主机卡片列表 -->
        <div>
          <div v-if="visibleHosts.length === 0" class="empty-state">
            <i class="fa fa-server"></i>
            <p>暂无监控主机数据</p>
          </div>

          <!-- 按环境分组显示主机卡片 -->
          <div v-for="env in environments" :key="env.key" class="environment-section">
            <div class="environment-header clickable" v-if="getHostsByEnvironment(env.key).length > 0" @click="toggleEnvironment(env.key)">
              <div class="header-left">
                <i class="fa fa-chevron-right expand-icon" :class="{ 'expanded': !collapsedEnvironments.has(env.key) }"></i>
                <h3><i class="fa fa-layer-group"></i> {{ env.name }}</h3>
              </div>
              <div class="env-stats">
                <span class="stat online">
                  <i class="fa fa-check-circle"></i>
                  在线: {{ getEnvOnlineCount(env.key) }}
                </span>
                <span class="stat total">
                  <i class="fa fa-server"></i>
                  总计: {{ getEnvTotalCount(env.key) }}
                </span>
              </div>
            </div>

            <!-- 按主机组分组显示 -->
            <div v-for="group in getGroupsByEnvironment(env.key)" :key="group.id" class="host-group-section" v-show="!collapsedEnvironments.has(env.key)">
              <div class="group-header clickable" v-if="getHostsByGroup(group.id).length > 0" @click="toggleGroup(group.id)">
                <div class="header-left">
                  <i class="fa fa-chevron-right expand-icon" :class="{ 'expanded': !collapsedGroups.has(group.id) }"></i>
                  <h4><i class="fa fa-folder"></i> {{ group.name }}</h4>
                </div>
                <div class="group-stats">
                  <span class="stat online">{{ getGroupOnlineCount(group.id) }}</span>
                  <span class="stat offline">{{ getGroupOfflineCount(group.id) }}</span>
                  <span class="stat total">{{ getGroupTotalCount(group.id) }}</span>
                </div>
              </div>

              <!-- 主机卡片网格 -->
              <div class="host-cards-grid" v-if="getHostsByGroup(group.id).length > 0" v-show="!collapsedGroups.has(group.id)">
                <div
                  v-for="host in getHostsByGroup(group.id)"
                  :key="host.id"
                  class="host-card glass-effect"
                  :class="getHostCardClass(getHostStatusFromAvailability(host.availability))"
                >
                  <div class="host-header">
                    <div class="host-info">
                      <h5 class="host-name">{{ host.hostname }}</h5>
                      <span class="host-ip">{{ host.ip_address }}</span>
                    </div>
                    <div class="host-status">
                      <i :class="getHostStatusIcon(getHostStatusFromAvailability(host.availability))" class="status-icon"></i>
                      <span class="status-text">{{ getHostStatusText(getHostStatusFromAvailability(host.availability)) }}</span>
                    </div>
                  </div>

                  <div class="host-metrics" v-if="host.metrics">
                    <div class="metric">
                      <span class="metric-label">CPU</span>
                      <span class="metric-value">{{ host.metrics.cpu_usage || 'N/A' }}%</span>
                    </div>
                    <div class="metric">
                      <span class="metric-label">内存</span>
                      <span class="metric-value">{{ host.metrics.memory_usage || 'N/A' }}%</span>
                    </div>
                    <div class="metric">
                      <span class="metric-label">磁盘</span>
                      <span class="metric-value">{{ host.metrics.disk_usage || 'N/A' }}%</span>
                    </div>
                  </div>

                  <div class="host-actions">
                    <button class="action-btn connect-btn" @click="connectToHost(host)" title="连接主机">
                      <i class="fa fa-terminal"></i>
                    </button>
                    <button class="action-btn monitor-btn" @click="viewHostDetails(host)" title="查看详情">
                      <i class="fa fa-chart-line"></i>
                    </button>
                    <button class="action-btn config-btn" @click="configureHost(host)" title="配置">
                      <i class="fa fa-cog"></i>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 未分组主机环境分组 -->
          <div v-if="getUngroupedHosts().length > 0 && showUnlinkedHosts" class="environment-section">
            <div class="environment-header clickable" @click="toggleEnvironment('ungrouped')">
              <div class="header-left">
                <i class="fa fa-chevron-right expand-icon" :class="{ 'expanded': !collapsedEnvironments.has('ungrouped') }"></i>
                <h3><i class="fa fa-question-circle"></i> 未分组主机</h3>
              </div>
              <div class="env-stats">
                <span class="stat online">
                  <i class="fa fa-check-circle"></i>
                  在线: {{ getUngroupedHosts().filter(host => getHostStatusFromAvailability(host.availability) === 'online').length }}
                </span>
                <span class="stat total">
                  <i class="fa fa-server"></i>
                  总计: {{ getUngroupedHosts().length }}
                </span>
              </div>
            </div>

            <!-- 未分组主机卡片网格 -->
            <div class="host-cards-grid" v-show="!collapsedEnvironments.has('ungrouped')">
              <div
                v-for="host in getUngroupedHosts()"
                :key="host.id"
                class="host-card glass-effect"
                :class="getHostCardClass(getHostStatusFromAvailability(host.availability))"
              >
                <div class="host-header">
                  <div class="host-info">
                    <h5 class="host-name">{{ host.hostname }}</h5>
                    <span class="host-ip">{{ host.ip_address }}</span>
                  </div>
                  <div class="host-status">
                    <i :class="getHostStatusIcon(getHostStatusFromAvailability(host.availability))" class="status-icon"></i>
                    <span class="status-text">{{ getHostStatusText(getHostStatusFromAvailability(host.availability)) }}</span>
                  </div>
                </div>

                <div class="host-metrics" v-if="host.metrics">
                  <div class="metric">
                    <span class="metric-label">CPU</span>
                    <span class="metric-value">{{ host.metrics.cpu_usage || 'N/A' }}%</span>
                  </div>
                  <div class="metric">
                    <span class="metric-label">内存</span>
                    <span class="metric-value">{{ host.metrics.memory_usage || 'N/A' }}%</span>
                  </div>
                  <div class="metric">
                    <span class="metric-label">磁盘</span>
                    <span class="metric-value">{{ host.metrics.disk_usage || 'N/A' }}%</span>
                  </div>
                </div>

                <div class="host-actions">
                  <button class="action-btn connect-btn" @click="connectToHost(host)" title="连接主机">
                    <i class="fa fa-terminal"></i>
                  </button>
                  <button class="action-btn monitor-btn" @click="viewHostDetails(host)" title="查看详情">
                    <i class="fa fa-chart-line"></i>
                  </button>
                  <button class="action-btn config-btn" @click="configureHost(host)" title="配置">
                    <i class="fa fa-cog"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 实时监控数据部分 -->
      <div class="realtime-section glass-effect" style="margin-bottom: 100px;">
        <div class="section-title">
          <i class="fa fa-chart-line"></i>
          实时监控数据
          <span class="auto-refresh-indicator">
            <i class="fa fa-sync-alt fa-spin" v-if="autoRefreshEnabled"></i>
            {{ autoRefreshEnabled ? '自动刷新中...' : '已停止自动刷新' }}
          </span>
        </div>

        <!-- 主机监控数据网格 -->
        <div class="monitoring-data-grid" v-if="hosts.length > 0">
          <div
            v-for="host in hosts"
            :key="host.id"
            class="host-monitoring-card glass-effect clickable"
            :class="getHostCardClass(getHostStatusFromAvailability(host.availability))"
            @click="showHostMetricsDialog(host)"
          >
            <div class="host-card-header">
              <div class="host-basic-info">
                <h4 class="host-name">{{ host.hostname }}</h4>
                <span class="host-ip">{{ host.ip_address }}</span>
              </div>
              <div class="host-status-badge" :class="'status-' + getHostStatusFromAvailability(host.availability)">
                <i :class="getHostStatusIcon(getHostStatusFromAvailability(host.availability))"></i>
                {{ getHostStatusText(getHostStatusFromAvailability(host.availability)) }}
              </div>
            </div>

            <!-- 监控指标数据 -->
            <div class="monitoring-metrics">
              <div class="metric-item">
                <div class="metric-label">
                  <i class="fa fa-microchip"></i>
                  CPU使用率
                </div>
                <div class="metric-value" :class="getMetricClass('cpu', host.cpu_usage)">
                  {{ formatMetricValue(host.cpu_usage, '%') }}
                </div>
              </div>

              <div class="metric-item">
                <div class="metric-label">
                  <i class="fa fa-memory"></i>
                  内存使用率
                </div>
                <div class="metric-value" :class="getMetricClass('memory', host.memory_usage)">
                  {{ formatMetricValue(host.memory_usage, '%') }}
                </div>
              </div>

              <div class="metric-item">
                <div class="metric-label">
                  <i class="fa fa-hdd"></i>
                  磁盘使用率
                </div>
                <div class="metric-value" :class="getMetricClass('disk', host.disk_usage)">
                  {{ formatMetricValue(host.disk_usage, '%') }}
                </div>
              </div>

              <div class="metric-item">
                <div class="metric-label">
                  <i class="fa fa-download"></i>
                  网络入流量
                </div>
                <div class="metric-value">
                  {{ formatMetricValue(host.network_in, '/s', true) }}
                </div>
              </div>

              <div class="metric-item">
                <div class="metric-label">
                  <i class="fa fa-upload"></i>
                  网络出流量
                </div>
                <div class="metric-value">
                  {{ formatMetricValue(host.network_out, '/s', true) }}
                </div>
              </div>

              <div class="metric-item">
                <div class="metric-label">
                  <i class="fa fa-tachometer-alt"></i>
                  系统负载
                </div>
                <div class="metric-value" :class="getMetricClass('load', host.load_average)">
                  {{ formatMetricValue(host.load_average) }}
                </div>
              </div>

              <!-- 显示主机基本信息 -->
              <div class="metric-item">
                <div class="metric-label">
                  <i class="fa fa-server"></i>
                  Zabbix主机ID
                </div>
                <div class="metric-value">
                  {{ host.zabbix_host_id || '未配置' }}
                </div>
              </div>

              <div class="metric-item">
                <div class="metric-label">
                  <i class="fa fa-clock"></i>
                  最后检查时间
                </div>
                <div class="metric-value">
                  {{ host.last_check_time ? formatTime(host.last_check_time) : '从未检查' }}
                </div>
              </div>
            </div>

            <!-- 最后更新时间 -->
            <div class="last-update">
              <i class="fa fa-clock"></i>
              最后更新: {{ formatTime(host.last_update || new Date()) }}
            </div>
          </div>
        </div>

        <!-- 无数据提示 -->
        <div v-else class="no-data-tip">
          <i class="fa fa-info-circle"></i>
          暂无监控数据，请检查主机配置和Zabbix连接状态
        </div>
      </div>
    </div>







    <!-- 主机监控指标详情弹窗 -->
    <el-dialog
      v-model="metricsDialogVisible"
      :title="`${selectedHost?.hostname || ''} - 详细监控指标`"
      width="85%"
      :before-close="handleCloseMetricsDialog"
      class="metrics-dialog glass-dialog"
    >
      <div class="metrics-dialog-content" v-if="selectedHost">
        <!-- 主机基本信息 -->
        <div class="host-info-section glass-effect">
          <h3><i class="fa fa-server"></i> 主机信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">主机名:</span>
              <span class="value">{{ selectedHost.hostname }}</span>
            </div>
            <div class="info-item">
              <span class="label">IP地址:</span>
              <span class="value">{{ selectedHost.ip_address }}</span>
            </div>
            <div class="info-item">
              <span class="label">状态:</span>
              <span class="value" :class="'status-' + getHostStatusFromAvailability(selectedHost.availability)">
                <i :class="getHostStatusIcon(getHostStatusFromAvailability(selectedHost.availability))"></i>
                {{ getHostStatusText(getHostStatusFromAvailability(selectedHost.availability)) }}
              </span>
            </div>
            <div class="info-item">
              <span class="label">Zabbix主机ID:</span>
              <span class="value">{{ selectedHost.zabbix_host_id || '未配置' }}</span>
            </div>
          </div>
        </div>

        <!-- 监控指标数据 -->
        <div class="metrics-section glass-effect">
          <div class="metrics-header">
            <h3><i class="fa fa-chart-line"></i> 监控指标</h3>
            <div class="metrics-controls">
              <!-- 搜索框 -->
              <div class="search-container" v-if="hostMetrics && hostMetrics.total_items">
                <el-input
                  v-model="metricsSearchText"
                  placeholder="搜索监控项..."
                  prefix-icon="Search"
                  clearable
                  size="small"
                  style="width: 250px;"
                  class="glass-input"
                />
              </div>
              <div class="metrics-stats" v-if="hostMetrics && hostMetrics.total_items">
                <span class="total-count">共 {{ hostMetrics.total_items }} 项指标</span>
                <button @click="refreshHostMetrics" class="refresh-btn glass-button" :disabled="loadingMetrics">
                  <i class="fa fa-sync-alt" :class="{ 'fa-spin': loadingMetrics }"></i>
                  刷新
                </button>
              </div>
            </div>
          </div>

          <div class="metrics-loading" v-if="loadingMetrics">
            <i class="fa fa-spinner fa-spin"></i>
            正在加载监控指标...
          </div>

          <div class="metrics-categories" v-else-if="hostMetrics && hostMetrics.metrics && Object.keys(hostMetrics.metrics).length > 0">
            <div
              v-for="(category, categoryKey) in filteredMetricsCategories"
              :key="categoryKey"
              class="metric-category"
            >
              <div class="category-header clickable" @click="toggleCategory(categoryKey)">
                <div class="category-title">
                  <i :class="getCategoryIcon(categoryKey)" class="category-icon"></i>
                  <span class="category-name">{{ category.name }}</span>
                  <span class="category-count">({{ category.items.length }})</span>
                </div>
                <i class="fa fa-chevron-right expand-icon" :class="{ 'expanded': !collapsedCategories.has(categoryKey) }"></i>
              </div>

              <div class="category-content" v-show="!collapsedCategories.has(categoryKey)">
                <div class="metrics-grid">
                  <div
                    v-for="item in category.items"
                    :key="item.key"
                    class="metric-card glass-effect"
                  >
                    <div class="metric-header">
                      <i :class="getMetricIcon(item.key, categoryKey)"></i>
                      <el-tooltip :content="item.name" placement="top" :disabled="item.name.length < 40">
                        <span class="metric-name">{{ truncateText(item.name, 40) }}</span>
                      </el-tooltip>
                    </div>
                    <div class="metric-value" :class="getMetricValueClass(item.value, item.key, categoryKey)">
                      <el-tooltip :content="item.value" placement="top" :disabled="String(item.value).length < 20">
                        <span>{{ truncateText(String(item.value), 20) }}</span>
                      </el-tooltip>
                    </div>
                    <div class="metric-key" v-if="item.key !== item.name">
                      <el-tooltip :content="item.key" placement="bottom" :disabled="item.key.length < 30">
                        <code>{{ truncateText(item.key, 30) }}</code>
                      </el-tooltip>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="no-metrics" v-else>
            <i class="fa fa-exclamation-triangle"></i>
            <p>暂无监控指标数据</p>
            <p class="hint">可能原因：主机离线、Zabbix Agent未运行或监控项配置异常</p>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="dialog-actions">
          <button @click="refreshHostMetrics" class="glass-button glass-button-secondary" :disabled="loadingMetrics">
            <i class="fa fa-refresh" :class="{ 'fa-spin': loadingMetrics }"></i>
            刷新数据
          </button>
          <button @click="connectToHost(selectedHost)" class="glass-button glass-button-primary">
            <i class="fa fa-terminal"></i>
            连接主机
          </button>
          <button @click="handleCloseMetricsDialog" class="glass-button">
            <i class="fa fa-times"></i>
            关闭
          </button>
        </div>
      </div>
    </el-dialog>

    <!-- 主机配置弹窗 -->
    <el-dialog
      v-model="configDialogVisible"
      :title="`配置主机 - ${selectedHost?.hostname || ''}`"
      width="80%"
      :before-close="handleCloseConfigDialog"
      class="config-dialog glass-dialog"
    >
      <div v-if="configLoading" class="loading-container">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>正在加载配置信息...</span>
      </div>

      <div v-else>
        <el-tabs v-model="activeConfigTab" @tab-click="handleConfigTabClick">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <div class="config-section glass-effect">
              <h3><i class="fa fa-info-circle"></i> 主机基本信息</h3>
              <el-form :model="hostConfig.basic" label-width="120px" class="config-form">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="主机名称">
                      <el-input v-model="hostConfig.basic.host" class="glass-input" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="可见名称">
                      <el-input v-model="hostConfig.basic.name" class="glass-input" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="描述">
                  <el-input v-model="hostConfig.basic.description" type="textarea" :rows="3" class="glass-input" />
                </el-form-item>
                <el-form-item label="状态">
                  <el-radio-group v-model="hostConfig.basic.status">
                    <el-radio :value="0">启用</el-radio>
                    <el-radio :value="1">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>

          <!-- 监控模板 -->
          <el-tab-pane label="监控模板" name="templates">
            <div class="config-section glass-effect">
              <div class="section-header">
                <h3><i class="fa fa-layer-group"></i> 监控模板管理</h3>
              </div>

              <!-- 模板搜索和添加区域 -->
              <div class="template-search-section">
                <div class="search-area">
                  <div class="search-input-group">
                    <el-input
                      v-model="templateSearchText"
                      placeholder="搜索模板名称或描述..."
                      prefix-icon="Search"
                      clearable
                      class="glass-input search-input"
                      @input="onTemplateSearch"
                    />
                    <div class="search-stats" v-if="templateSearchText">
                      找到 {{ filteredTemplates.length }} 个模板
                    </div>
                  </div>
                </div>

                <div class="add-template-controls">
                  <el-select
                    v-model="selectedTemplateToAdd"
                    placeholder="从搜索结果中选择模板"
                    style="width: 350px; margin-right: 12px;"
                    class="glass-select template-select"
                    :disabled="filteredTemplates.length === 0"
                    popper-class="template-dropdown"
                  >
                    <el-option
                      v-for="template in filteredTemplates"
                      :key="template.templateid"
                      :label="template.name"
                      :value="template.templateid"
                      class="template-option-item"
                    >
                      <div class="template-option">
                        <div class="template-option-name" :title="template.name">
                          <span v-html="highlightSearchText(truncateTemplateName(template.name), templateSearchText)"></span>
                        </div>
                        <div class="template-option-desc" :title="template.description">
                          <span v-html="highlightSearchText(truncateText(template.description || '无描述', 40), templateSearchText)"></span>
                        </div>
                      </div>
                    </el-option>
                  </el-select>
                  <el-button @click="addSelectedTemplate" class="glass-button add-button" :disabled="!selectedTemplateToAdd">
                    <i class="fa fa-plus"></i>
                    添加模板
                  </el-button>
                </div>

                <!-- 快速模板分类 -->
                <div class="template-categories" v-if="!templateSearchText">
                  <div class="category-title">常用模板分类：</div>
                  <div class="category-tags">
                    <el-tag
                      v-for="category in templateCategories"
                      :key="category.name"
                      @click="quickSearchTemplate(category.keyword)"
                      class="category-tag"
                      :type="category.type"
                      effect="plain"
                    >
                      {{ category.name }} ({{ category.count }})
                    </el-tag>
                  </div>
                </div>
              </div>

              <div class="templates-list">
                <div v-for="template in hostConfig.templates" :key="template.templateid" class="template-item glass-effect">
                  <div class="template-info">
                    <div class="template-name">{{ template.name }}</div>
                    <div class="template-desc">{{ template.description || '无描述' }}</div>
                  </div>
                  <div class="template-actions">
                    <el-button size="small" @click="removeTemplate(template)" class="action-glass-button danger">
                      <i class="fa fa-trash"></i>
                      移除
                    </el-button>
                  </div>
                </div>

                <div v-if="hostConfig.templates.length === 0" class="empty-state">
                  <i class="fa fa-layer-group"></i>
                  <p>暂无监控模板</p>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 主机组 -->
          <el-tab-pane label="主机组" name="hostgroups">
            <div class="config-section glass-effect">
              <div class="section-header">
                <h3><i class="fa fa-users"></i> 主机组管理</h3>
              </div>

              <!-- 主机组搜索和添加区域 -->
              <div class="hostgroup-search-section">
                <div class="search-area">
                  <div class="search-input-group">
                    <el-input
                      v-model="hostgroupSearchText"
                      placeholder="搜索主机组名称..."
                      prefix-icon="Search"
                      clearable
                      class="glass-input search-input"
                      @input="onHostgroupSearch"
                    />
                    <div class="search-stats" v-if="hostgroupSearchText">
                      找到 {{ filteredHostgroups.length }} 个主机组
                    </div>
                  </div>
                </div>

                <div class="add-hostgroup-controls">
                  <el-select
                    v-model="selectedHostgroupToAdd"
                    placeholder="从搜索结果中选择主机组"
                    style="width: 350px; margin-right: 12px;"
                    class="glass-select hostgroup-select"
                    :disabled="filteredHostgroups.length === 0"
                    popper-class="hostgroup-dropdown"
                  >
                    <el-option
                      v-for="group in filteredHostgroups"
                      :key="group.groupid"
                      :label="group.name"
                      :value="group.groupid"
                      class="hostgroup-option-item"
                    >
                      <div class="hostgroup-option">
                        <div class="hostgroup-option-name" :title="group.name">
                          <span v-html="highlightSearchText(truncateText(group.name, 35), hostgroupSearchText)"></span>
                        </div>
                      </div>
                    </el-option>
                  </el-select>
                  <el-button @click="addSelectedHostgroup" class="glass-button add-button" :disabled="!selectedHostgroupToAdd">
                    <i class="fa fa-plus"></i>
                    添加主机组
                  </el-button>
                </div>

                <!-- 快速主机组分类 -->
                <div class="hostgroup-categories" v-if="!hostgroupSearchText">
                  <div class="category-title">常用主机组分类：</div>
                  <div class="category-tags">
                    <el-tag
                      v-for="category in hostgroupCategories"
                      :key="category.name"
                      @click="quickSearchHostgroup(category.keyword)"
                      class="category-tag"
                      :type="category.type"
                      effect="plain"
                    >
                      {{ category.name }} ({{ category.count }})
                    </el-tag>
                  </div>
                </div>
              </div>

              <div class="hostgroups-list">
                <div v-for="group in hostConfig.hostgroups" :key="group.groupid" class="hostgroup-item glass-effect">
                  <div class="hostgroup-info">
                    <div class="hostgroup-name">{{ group.name }}</div>
                  </div>
                  <div class="hostgroup-actions">
                    <el-button size="small" @click="removeHostgroup(group)" class="action-glass-button danger">
                      <i class="fa fa-trash"></i>
                      移除
                    </el-button>
                  </div>
                </div>

                <div v-if="hostConfig.hostgroups.length === 0" class="empty-state">
                  <i class="fa fa-users"></i>
                  <p>暂无主机组</p>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 接口配置 -->
          <el-tab-pane label="接口配置" name="interfaces">
            <div class="config-section glass-effect">
              <div class="section-header">
                <h3><i class="fa fa-network-wired"></i> 主机接口配置</h3>
                <el-button @click="addInterface" class="glass-button add-button">
                  <i class="fa fa-plus"></i>
                  添加接口
                </el-button>
              </div>

              <div class="interfaces-list">
                <div v-for="(interfaceItem, index) in hostConfig.interfaces" :key="interfaceItem.interfaceid || index" class="interface-item glass-effect">
                  <div class="interface-header">
                    <div class="interface-type">
                      <el-tag :type="getInterfaceTypeColor(interfaceItem.type)" size="small">
                        {{ getInterfaceTypeName(interfaceItem.type) }}
                      </el-tag>
                      <el-tag v-if="interfaceItem.main === '1'" type="success" size="small">主接口</el-tag>
                    </div>
                    <div class="interface-actions">
                      <el-button size="small" @click="editInterface(interfaceItem, index)" class="action-glass-button primary">
                        <i class="fa fa-edit"></i>
                        编辑
                      </el-button>
                      <el-button size="small" @click="removeInterface(index)" class="action-glass-button danger">
                        <i class="fa fa-trash"></i>
                        删除
                      </el-button>
                    </div>
                  </div>

                  <div class="interface-details">
                    <div class="interface-info">
                      <div class="info-item">
                        <span class="label">连接方式:</span>
                        <span class="value">{{ interfaceItem.useip === '1' ? 'IP地址' : 'DNS名称' }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">地址:</span>
                        <span class="value">{{ interfaceItem.useip === '1' ? interfaceItem.ip : interfaceItem.dns }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">端口:</span>
                        <span class="value">{{ interfaceItem.port }}</span>
                      </div>
                    </div>
                  </div>
                </div>

                <div v-if="hostConfig.interfaces.length === 0" class="empty-state">
                  <i class="fa fa-network-wired"></i>
                  <p>暂无接口配置</p>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 宏变量管理 -->
          <el-tab-pane label="宏变量" name="macros">
            <div class="config-section glass-effect">
              <div class="section-header">
                <h3><i class="fa fa-code"></i> 宏变量管理</h3>
                <el-button @click="addMacro" class="glass-button add-button">
                  <i class="fa fa-plus"></i>
                  添加宏变量
                </el-button>
              </div>

              <div class="macros-list">
                <div v-for="(macro, index) in hostConfig.macros" :key="index" class="macro-item glass-effect">
                  <div class="macro-content">
                    <div class="macro-name">{{ macro.macro }}</div>
                    <div class="macro-value">{{ macro.value || '(空值)' }}</div>
                    <div class="macro-desc">{{ macro.description || '无描述' }}</div>
                  </div>
                  <div class="macro-actions">
                    <el-button size="small" @click="editMacro(macro, index)" class="action-glass-button primary">
                      <i class="fa fa-edit"></i>
                      编辑
                    </el-button>
                    <el-button size="small" @click="removeMacro(index)" class="action-glass-button danger">
                      <i class="fa fa-trash"></i>
                      删除
                    </el-button>
                  </div>
                </div>

                <div v-if="hostConfig.macros.length === 0" class="empty-state">
                  <i class="fa fa-code"></i>
                  <p>暂无宏变量</p>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 监控项管理 -->
          <el-tab-pane label="监控项" name="items">
            <div class="config-section glass-effect">
              <div class="section-header">
                <h3><i class="fa fa-chart-line"></i> 监控项管理</h3>
                <div class="items-search">
                  <el-input
                    v-model="itemsSearchText"
                    placeholder="搜索监控项..."
                    prefix-icon="Search"
                    clearable
                    class="glass-input"
                    style="width: 300px;"
                    @input="handleItemsSearch"
                    @clear="handleItemsSearchClear"
                  />
                </div>
              </div>

              <!-- 监控项分类统计 -->
              <div class="items-summary" v-if="itemsTotal > 0">
                <div class="summary-item">
                  <span class="summary-label">主机启用文件监控:</span>
                  <span class="summary-count">{{ itemsTotal }} 个</span>
                </div>
                <div class="summary-item">
                  <span class="summary-label">当前页显示:</span>
                  <span class="summary-count">{{ hostItems.length }} 个</span>
                </div>
                <div class="summary-item">
                  <span class="summary-label">启用状态:</span>
                  <span class="summary-count success">{{ hostItems.filter(item => item.status === 0).length }} 个</span>
                </div>
                <div class="summary-item">
                  <span class="summary-label">禁用状态:</span>
                  <span class="summary-count danger">{{ hostItems.filter(item => item.status === 1).length }} 个</span>
                </div>
              </div>

              <div class="items-list" v-loading="itemsLoading">
                <!-- 主机自定义监控项 -->
                <div v-if="hostCustomItems.length > 0" class="items-category">
                  <h5 class="category-title">
                    <i class="fa fa-server"></i>
                    主机自定义监控项 ({{ hostCustomItems.length }})
                  </h5>
                  <div v-for="item in hostCustomItems" :key="item.itemid" class="item-row glass-effect custom-item">
                    <div class="item-info">
                      <div class="item-name">{{ item.name }}</div>
                      <div class="item-key">{{ item.key_ }}</div>
                      <div class="item-type">{{ getItemTypeName(item.type) }}</div>
                    </div>
                    <div class="item-status">
                      <el-tag
                        :type="item.status === 0 ? 'success' : 'danger'"
                        size="small"
                      >
                        {{ item.status === 0 ? '启用' : '禁用' }}
                      </el-tag>
                    </div>
                    <div class="item-actions">
                      <el-button
                        size="small"
                        @click="toggleItemStatus(item)"
                        :class="item.status === 0 ? 'action-glass-button warning' : 'action-glass-button success'"
                      >
                        <i :class="item.status === 0 ? 'fa fa-pause' : 'fa fa-play'"></i>
                        {{ item.status === 0 ? '禁用' : '启用' }}
                      </el-button>
                      <el-button size="small" @click="viewItemDetails(item)" class="action-glass-button info">
                        <i class="fa fa-eye"></i>
                        详情
                      </el-button>
                      <el-button size="small" @click="deleteCustomItem(item)" class="action-glass-button danger">
                        <i class="fa fa-trash"></i>
                        删除
                      </el-button>
                    </div>
                  </div>
                </div>

                <!-- 模板继承监控项 -->
                <div v-if="templateInheritedItems.length > 0" class="items-category">
                  <h5 class="category-title">
                    <i class="fa fa-layer-group"></i>
                    模板继承监控项 ({{ templateInheritedItems.length }})
                  </h5>
                  <div v-for="item in templateInheritedItems" :key="item.itemid" class="item-row glass-effect template-item">
                    <div class="item-info">
                      <div class="item-name">{{ item.name }}</div>
                      <div class="item-key">{{ item.key_ }}</div>
                      <div class="item-type">{{ getItemTypeName(item.type) }}</div>
                    </div>
                    <div class="item-status">
                      <el-tag
                        :type="item.status === 0 ? 'success' : 'danger'"
                        size="small"
                      >
                        {{ item.status === 0 ? '启用' : '禁用' }}
                      </el-tag>
                    </div>
                    <div class="item-actions">
                      <el-button
                        size="small"
                        @click="toggleItemStatus(item)"
                        :class="item.status === 0 ? 'action-glass-button warning' : 'action-glass-button success'"
                      >
                        <i :class="item.status === 0 ? 'fa fa-pause' : 'fa fa-play'"></i>
                        {{ item.status === 0 ? '禁用' : '启用' }}
                      </el-button>
                      <el-button size="small" @click="viewItemDetails(item)" class="action-glass-button info">
                        <i class="fa fa-eye"></i>
                        详情
                      </el-button>
                      <el-tag type="info" size="small">模板项</el-tag>
                    </div>
                  </div>
                </div>

                <div v-if="hostItems.length === 0 && !itemsLoading" class="empty-state">
                  <i class="fa fa-chart-line"></i>
                  <p>暂无监控项</p>
                </div>
              </div>

              <!-- 分页组件 -->
              <div v-if="itemsTotal > 0" class="items-pagination">
                <el-pagination
                  v-model:current-page="itemsCurrentPage"
                  v-model:page-size="itemsPageSize"
                  :page-sizes="[20, 50, 100, 200]"
                  :total="itemsTotal"
                  layout="total, sizes, prev, pager, next, jumper"
                  background
                  class="glass-pagination"
                  @current-change="handleItemsPageChange"
                  @size-change="handleItemsPageSizeChange"
                />
              </div>
            </div>
          </el-tab-pane>



        </el-tabs>
      </div>

      <template #footer>
        <div class="dialog-actions">
          <el-button @click="handleCloseConfigDialog" class="glass-button">
            <i class="fa fa-times"></i>
            取消
          </el-button>
          <el-button @click="saveHostConfiguration" class="glass-button save-button" :loading="configLoading">
            <i class="fa fa-save"></i>
            保存配置
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加监控项对话框 -->
    <el-dialog
      v-model="addItemDialogVisible"
      title="添加监控项"
      width="800px"
      class="glass-dialog"
      :close-on-click-modal="false"
    >
      <div class="add-item-content">
        <div class="item-templates-section">
          <h4><i class="fa fa-list"></i> 选择监控项模板</h4>
          <div class="template-categories">
            <el-button
              v-for="category in itemCategories"
              :key="category.name"
              @click="selectItemCategory(category.name)"
              :class="selectedItemCategory === category.name ? 'glass-button active' : 'glass-button'"
              size="small"
            >
              {{ category.name }} ({{ category.count }})
            </el-button>
          </div>

          <div class="item-search">
            <el-input
              v-model="itemTemplateSearchText"
              placeholder="搜索监控项模板..."
              prefix-icon="Search"
              clearable
              class="glass-input"
            />
          </div>

          <div class="item-templates-list">
            <div
              v-for="template in filteredItemTemplates"
              :key="template.key"
              class="item-template-card glass-effect"
              @click="selectItemTemplate(template)"
              :class="{ 'selected': selectedItemTemplate?.key === template.key }"
            >
              <div class="template-info">
                <div class="template-name">{{ template.name }}</div>
                <div class="template-key">{{ template.key }}</div>
                <div class="template-description">{{ template.description || '无描述' }}</div>
              </div>
              <div class="template-type">
                <el-tag :type="getItemTypeColor(template.type)" size="small">
                  {{ getItemTypeName(template.type) }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <div v-if="selectedItemTemplate" class="item-config-section">
          <h4><i class="fa fa-cog"></i> 监控项配置</h4>
          <el-form :model="newItemConfig" label-width="120px" class="glass-form">
            <el-form-item label="监控项名称">
              <el-input v-model="newItemConfig.name" class="glass-input" />
            </el-form-item>
            <el-form-item label="键值">
              <el-input v-model="newItemConfig.key" class="glass-input" />
            </el-form-item>
            <el-form-item label="更新间隔">
              <el-input v-model="newItemConfig.delay" class="glass-input" placeholder="30s" />
            </el-form-item>
            <el-form-item label="历史保存期">
              <el-input v-model="newItemConfig.history" class="glass-input" placeholder="90d" />
            </el-form-item>
            <el-form-item label="趋势保存期">
              <el-input v-model="newItemConfig.trends" class="glass-input" placeholder="365d" />
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="newItemConfig.description" type="textarea" class="glass-input" />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addItemDialogVisible = false" class="glass-button">取消</el-button>
          <el-button
            @click="confirmAddItem"
            :disabled="!selectedItemTemplate"
            class="glass-button primary"
            :loading="addingItem"
          >
            添加监控项
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 接口编辑对话框 -->
    <el-dialog
      v-model="showInterfaceDialog"
      title="编辑接口配置"
      width="600px"
      class="glass-dialog"
      :close-on-click-modal="false"
    >
      <div class="interface-edit-form">
        <el-form :model="interfaceForm" label-width="120px" class="glass-form">
          <el-form-item label="接口类型">
            <el-select v-model="interfaceForm.type" class="glass-select" style="width: 100%;">
              <el-option label="Zabbix Agent" value="1" />
              <el-option label="SNMP" value="2" />
              <el-option label="IPMI" value="3" />
              <el-option label="JMX" value="4" />
            </el-select>
          </el-form-item>

          <el-form-item label="连接方式">
            <el-radio-group v-model="interfaceForm.useip" class="glass-radio-group">
              <el-radio label="1">使用IP地址</el-radio>
              <el-radio label="0">使用DNS名称</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="interfaceForm.useip === '1'" label="IP地址">
            <el-input
              v-model="interfaceForm.ip"
              placeholder="请输入IP地址"
              class="glass-input"
            />
          </el-form-item>

          <el-form-item v-if="interfaceForm.useip === '0'" label="DNS名称">
            <el-input
              v-model="interfaceForm.dns"
              placeholder="请输入DNS名称"
              class="glass-input"
            />
          </el-form-item>

          <el-form-item label="端口">
            <el-input
              v-model="interfaceForm.port"
              placeholder="请输入端口号"
              class="glass-input"
              style="width: 200px;"
            />
          </el-form-item>

          <el-form-item label="主接口">
            <el-switch
              v-model="interfaceForm.main"
              active-value="1"
              inactive-value="0"
              active-text="是"
              inactive-text="否"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelInterfaceEdit" class="glass-button cancel-button">
            <i class="fa fa-times"></i>
            取消
          </el-button>
          <el-button @click="saveInterfaceEdit" class="glass-button save-button">
            <i class="fa fa-save"></i>
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 主机管理对话框 -->
    <el-dialog
      v-model="hostManagementDialog"
      title="主机管理"
      width="800px"
      class="glass-dialog"
    >
      <div class="host-management-content glass-effect">
        <div class="management-header">
          <h4><i class="fa fa-server"></i> 主机关联管理</h4>
          <p class="description">管理Zabbix主机与CMDB的关联关系</p>
        </div>

        <!-- 统计信息 -->
        <div class="management-stats">
          <div class="stat-item">
            <span class="stat-label">Zabbix总主机:</span>
            <span class="stat-value">{{ hostLinkageStats.total || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">已关联:</span>
            <span class="stat-value success">{{ hostLinkageStats.linked || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">待关联:</span>
            <span class="stat-value warning">{{ hostLinkageStats.unlinked || 0 }}</span>
          </div>
        </div>

        <!-- 快速操作 -->
        <div class="quick-actions">
          <el-button @click="handleSyncCommand('auto')" type="primary" :loading="loading.sync">
            <i class="fa fa-magic"></i>
            一键智能关联
          </el-button>
          <el-button @click="refreshData" :loading="loading.refresh">
            <i class="fa fa-refresh"></i>
            刷新数据
          </el-button>
        </div>

        <!-- 待关联主机列表 -->
        <div class="unlinked-hosts-section" v-if="hostLinkageStats.unlinked > 0">
          <h5><i class="fa fa-unlink"></i> 待关联主机</h5>
          <div class="host-list">
            <div class="host-item" v-for="host in unlinkedHosts" :key="host.id">
              <div class="host-info">
                <span class="hostname">{{ host.hostname }}</span>
                <span class="ip">{{ host.ip_address }}</span>
              </div>
              <el-button @click="quickAssociate(host)" size="small" type="primary">
                快速关联
              </el-button>
            </div>
          </div>
        </div>

        <div v-else class="no-unlinked">
          <i class="fa fa-check-circle"></i>
          <p>所有主机都已关联！</p>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="hostManagementDialog = false" class="glass-button">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 自动刷新设置对话框 -->
    <el-dialog
      v-model="autoRefreshDialog"
      title="自动刷新设置"
      width="500px"
      class="glass-dialog"
    >
      <div class="auto-refresh-content glass-effect">
        <div class="setting-item">
          <label class="setting-label">
            <el-switch v-model="autoRefreshSettings.enabled" />
            启用自动刷新
          </label>
        </div>

        <div class="setting-item interval-setting" v-if="autoRefreshSettings.enabled">
          <label class="setting-label">刷新间隔（秒）:</label>
          <el-input-number
            v-model="autoRefreshSettings.interval"
            :min="10"
            :max="300"
            :step="10"
            style="width: 180px;"
          />
        </div>

        <div class="setting-item" v-if="autoRefreshSettings.enabled">
          <label class="setting-label">
            <el-switch v-model="autoRefreshSettings.onlyWhenVisible" />
            仅在页面可见时刷新
          </label>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="autoRefreshDialog = false" class="glass-button">
            取消
          </el-button>
          <el-button @click="saveAutoRefreshSettings" type="primary" class="glass-button">
            保存设置
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { hostAPI } from '@/api/host'
import { monitoringApi } from '@/api/monitoring'
import { monitoringWebSocket } from '@/utils/websocket'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, h, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'

// 路由实例
const router = useRouter()

// 响应式数据
const loading = ref({
  refresh: false,
  sync: false
})
const filterStatus = ref('')
const searchKeyword = ref('')

// 新增显示控制相关数据
const displayMode = ref('grouped') // grouped, flat, table
const showUnlinkedHosts = ref(false)
const displayFilter = ref('all') // all, linked, unlinked
const selectedEnvironment = ref('')
const hostManagementDialog = ref(false)
const autoRefreshDialog = ref(false)
const isDevelopment = ref(process.env.NODE_ENV === 'development')

// 自动刷新设置
const autoRefreshSettings = ref({
  enabled: false,
  interval: 30, // 秒
  onlyWhenVisible: true
})

// 自动刷新定时器
const autoRefreshTimer = ref<NodeJS.Timeout | null>(null)

// 树形结构相关
const hostTreeRef = ref()
const expandedKeys = ref([])
const treeProps = {
  children: 'children',
  label: 'label'
}

// 折叠状态管理
const collapsedEnvironments = ref(new Set())
const collapsedGroups = ref(new Set())

// 统计数据
const statistics = reactive({
  total_hosts: 0,
  online_hosts: 0,
  offline_hosts: 0,
  alert_hosts: 0
})

// 主机关联统计数据（计算属性）
const hostLinkageStats = computed(() => {
  const total = hosts.value.length
  const linked = hosts.value.filter(host => host.cmdb_linked).length
  const unlinked = total - linked

  return {
    total,
    linked,
    unlinked
  }
})

// 主机列表
const hosts = ref([])
const hostGroups = ref([])

// Zabbix服务器管理
const zabbixServers = ref([])
const selectedZabbixServer = ref('')

// 监控指标弹窗相关
const metricsDialogVisible = ref(false)
const selectedHost = ref(null)
const hostMetrics = ref({})
const loadingMetrics = ref(false)
const collapsedCategories = ref(new Set())
const metricsSearchText = ref('')

// 主机配置弹窗相关
const configDialogVisible = ref(false)
const configLoading = ref(false)
const hostConfig = ref({
  basic: {
    host: '',
    name: '',
    description: '',
    status: 0
  },
  templates: [],
  hostgroups: [],
  interfaces: [],
  macros: []
})
const availableTemplates = ref([])
const availableHostgroups = ref([])
const selectedTemplateToAdd = ref('')
const selectedHostgroupToAdd = ref('')
const templateSearchText = ref('')
const hostgroupSearchText = ref('')
const itemsSearchText = ref('')
const hostItems = ref([])
const editingInterface = ref(null)
const editingMacro = ref(null)
const showInterfaceDialog = ref(false)
const interfaceForm = ref({
  type: '1',
  main: '0',
  useip: '1',
  ip: '',
  dns: '',
  port: '10050'
})

// 监控项分页相关
const itemsCurrentPage = ref(1)
const itemsPageSize = ref(50)
const itemsTotal = ref(0)
const itemsLoading = ref(false)

// 添加监控项对话框相关
const addItemDialogVisible = ref(false)
const selectedItemTemplate = ref('')
const addingItem = ref(false)

// 文本截断函数
const truncateText = (text: string, maxLength: number) => {
  if (!text || text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 过滤监控指标分类
const filteredMetricsCategories = computed(() => {
  if (!hostMetrics.value?.metrics) return {}

  const searchText = metricsSearchText.value.toLowerCase().trim()
  if (!searchText) return hostMetrics.value.metrics

  const filtered = {}

  Object.keys(hostMetrics.value.metrics).forEach(categoryKey => {
    const category = hostMetrics.value.metrics[categoryKey]
    const filteredItems = category.items.filter(item =>
      item.name.toLowerCase().includes(searchText) ||
      item.key.toLowerCase().includes(searchText) ||
      String(item.value).toLowerCase().includes(searchText)
    )

    if (filteredItems.length > 0) {
      filtered[categoryKey] = {
        ...category,
        items: filteredItems
      }
    }
  })

  return filtered
})

// 可添加的模板列表（排除已关联的）
const availableTemplatesForAdd = computed(() => {
  return availableTemplates.value.filter(template =>
    !hostConfig.value.templates.find(t => t.templateid === template.templateid)
  )
})

// 可添加的主机组列表（排除已关联的）
const availableHostgroupsForAdd = computed(() => {
  return availableHostgroups.value.filter(group =>
    !hostConfig.value.hostgroups.find(g => g.groupid === group.groupid)
  )
})

// 过滤后的模板列表
const filteredTemplates = computed(() => {
  const searchText = templateSearchText.value.toLowerCase().trim()
  if (!searchText) return availableTemplatesForAdd.value

  return availableTemplatesForAdd.value.filter(template =>
    template.name.toLowerCase().includes(searchText) ||
    (template.description && template.description.toLowerCase().includes(searchText))
  )
})

// 过滤后的主机组列表
const filteredHostgroups = computed(() => {
  const searchText = hostgroupSearchText.value.toLowerCase().trim()
  if (!searchText) return availableHostgroupsForAdd.value

  return availableHostgroupsForAdd.value.filter(group =>
    group.name.toLowerCase().includes(searchText)
  )
})

// 模板名称截断函数
const truncateTemplateName = (name: string) => {
  if (!name) return ''
  // 移除常见的前缀
  let cleanName = name.replace(/^Template\s+/i, '').replace(/^Zabbix\s+/i, '')
  return truncateText(cleanName, 30)
}

// 模板过滤函数
const filterTemplates = (query: string) => {
  templateSearchText.value = query
}

// 主机组过滤函数
const filterHostgroups = (query: string) => {
  hostgroupSearchText.value = query
}

// 搜索处理函数
const onTemplateSearch = () => {
  selectedTemplateToAdd.value = '' // 清空选择
}

const onHostgroupSearch = () => {
  selectedHostgroupToAdd.value = '' // 清空选择
}

// 高亮搜索文本
const highlightSearchText = (text: string, searchText: string) => {
  if (!searchText || !text) return text

  const regex = new RegExp(`(${searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi')
  return text.replace(regex, '<mark class="search-highlight">$1</mark>')
}

// 快速搜索模板
const quickSearchTemplate = (keyword: string) => {
  templateSearchText.value = keyword
  selectedTemplateToAdd.value = ''
}

// 快速搜索主机组
const quickSearchHostgroup = (keyword: string) => {
  hostgroupSearchText.value = keyword
  selectedHostgroupToAdd.value = ''
}

// 模板分类计算属性
const templateCategories = computed(() => {
  const categories = [
    { name: 'Linux', keyword: 'linux', type: 'success', count: 0 },
    { name: 'Windows', keyword: 'windows', type: 'primary', count: 0 },
    { name: 'Database', keyword: 'db', type: 'warning', count: 0 },
    { name: 'Web Server', keyword: 'apache|nginx|web', type: 'info', count: 0 },
    { name: 'Network', keyword: 'network|switch|router', type: 'danger', count: 0 },
    { name: 'Application', keyword: 'app|application', type: '', count: 0 }
  ]

  categories.forEach(category => {
    const regex = new RegExp(category.keyword, 'i')
    category.count = availableTemplatesForAdd.value.filter(template =>
      regex.test(template.name) || regex.test(template.description || '')
    ).length
  })

  return categories.filter(cat => cat.count > 0)
})

// 主机组分类计算属性
const hostgroupCategories = computed(() => {
  const categories = [
    { name: 'Linux', keyword: 'linux', type: 'success', count: 0 },
    { name: 'Windows', keyword: 'windows', type: 'primary', count: 0 },
    { name: 'Database', keyword: 'db|database', type: 'warning', count: 0 },
    { name: 'Web', keyword: 'web|www', type: 'info', count: 0 },
    { name: 'Production', keyword: 'prod|production', type: 'danger', count: 0 },
    { name: 'Development', keyword: 'dev|development|test', type: '', count: 0 }
  ]

  categories.forEach(category => {
    const regex = new RegExp(category.keyword, 'i')
    category.count = availableHostgroupsForAdd.value.filter(group =>
      regex.test(group.name)
    ).length
  })

  return categories.filter(cat => cat.count > 0)
})

// 主机自定义监控项
const hostCustomItems = computed(() => {
  return hostItems.value.filter(item => item.source === 'host')
})

// 模板继承监控项
const templateInheritedItems = computed(() => {
  return hostItems.value.filter(item => item.source === 'template')
})

// 接口类型名称映射
const getInterfaceTypeName = (type) => {
  const types = {
    '1': 'Zabbix Agent',
    '2': 'SNMP',
    '3': 'IPMI',
    '4': 'JMX'
  }
  return types[type] || '未知'
}

// 接口类型颜色映射
const getInterfaceTypeColor = (type) => {
  const colors = {
    '1': 'primary',
    '2': 'warning',
    '3': 'danger',
    '4': 'info'
  }
  return colors[type] || ''
}

// 监控项类型名称映射
const getItemTypeName = (type) => {
  const types = {
    '0': 'Zabbix Agent',
    '1': 'SNMPv1 Agent',
    '2': 'Zabbix Trapper',
    '3': 'Simple Check',
    '4': 'SNMPv2 Agent',
    '5': 'Zabbix Internal',
    '6': 'SNMPv3 Agent',
    '7': 'Zabbix Agent (Active)',
    '8': 'Zabbix Aggregate',
    '9': 'Web Item',
    '10': 'External Check',
    '11': 'Database Monitor',
    '12': 'IPMI Agent',
    '13': 'SSH Agent',
    '14': 'TELNET Agent',
    '15': 'Calculated',
    '16': 'JMX Agent',
    '17': 'SNMP Trap',
    '18': 'Dependent Item',
    '19': 'HTTP Agent',
    '20': 'SNMP Agent'
  }
  return types[type] || '未知类型'
}

// 构建树形数据
const hostTreeData = computed(() => {
  console.log('开始构建监控主机树形数据，主机总数:', hosts.value.length, '主机组数:', hostGroups.value?.length || 0)

  // 确保hostGroups是数组
  if (!Array.isArray(hostGroups.value) || hostGroups.value.length === 0) {
    console.log('主机组数据为空或不是数组，返回空树')
    return []
  }

  // 环境名称映射
  const envNames = {
    'dev': '开发环境',
    'test': '测试环境',
    'staging': '预发布环境',
    'prod': '生产环境'
  }

  // 1. 先获取所有存在的环境
  const existingEnvironments = [...new Set(hostGroups.value.map(group => group.environment))].filter(Boolean)
  console.log('存在的环境:', existingEnvironments)

  const treeResult = existingEnvironments.map(envKey => {
    // 2. 获取该环境下的所有主机组
    const envGroups = hostGroups.value.filter(group => group.environment === envKey)
    console.log(`环境 ${envKey} 下的主机组:`, envGroups)

    let totalHosts = 0
    let onlineHosts = 0
    let offlineHosts = 0

    const children = envGroups.map(group => {
      // 3. 获取该主机组下的监控主机
      const groupHosts = hosts.value.filter(host => {
        // 通过主机名匹配CMDB主机和监控主机
        return group.hosts && group.hosts.some(cmdbHost => cmdbHost.hostname === host.hostname)
      })

      console.log(`主机组 ${group.name} 下的监控主机数量:`, groupHosts.length)

      // 统计主机状态
      const groupOnline = groupHosts.filter(host => host.status === 'online').length
      const groupOffline = groupHosts.length - groupOnline

      totalHosts += groupHosts.length
      onlineHosts += groupOnline
      offlineHosts += groupOffline

      return {
        id: `group-${group.id}`,
        label: group.name,
        type: 'group',
        environment: envKey,
        hostCount: groupHosts.length,
        children: groupHosts.map(host => ({
          id: `host-${host.id}`,
          label: `${host.hostname} (${host.ip_address})`,
          type: 'host',
          hostname: host.hostname,
          ip_address: host.ip_address,
          status: host.status,
          availability: host.availability,
          monitoring_status: host.monitoring_status,
          monitoring_status_display: host.monitoring_status_display,
          zabbix_server_name: host.zabbix_server_name,
          last_check_time: host.last_check_time,
          total_items: host.total_items,
          total_triggers: host.total_triggers,
          active_alerts: host.active_alerts,
          hostData: host
        }))
      }
    })

    return {
      id: envKey,
      label: envNames[envKey] || envKey,
      type: 'environment',
      environment: envKey,
      totalHosts,
      onlineHosts,
      offlineHosts,
      children: children
    }
  })

  console.log('构建的监控主机树形数据:', treeResult)
  return treeResult
})

// 计算属性
const filteredHosts = computed(() => {
  let filtered = hosts.value

  // 状态筛选
  if (filterStatus.value) {
    filtered = filtered.filter(host => {
      const status = getHostStatusFromAvailability(host.availability)
      return status === filterStatus.value
    })
  }

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(host =>
      host.hostname.toLowerCase().includes(keyword) ||
      (host.ip_address && host.ip_address.toLowerCase().includes(keyword))
    )
  }

  return filtered
})

// 未关联主机列表
const unlinkedHosts = computed(() => {
  return hosts.value.filter(host => !host.cmdb_linked)
})

// 自动刷新状态计算属性
const autoRefreshEnabled = computed(() => {
  return autoRefreshSettings.value.enabled && autoRefreshTimer.value !== null
})

// 可见主机列表（根据显示设置过滤）
const visibleHosts = computed(() => {
  let filtered = hosts.value

  // 环境过滤
  if (selectedEnvironment.value) {
    filtered = filtered.filter(host =>
      host.host_groups && host.host_groups.some(group => group.environment === selectedEnvironment.value)
    )
  }

  // 关联状态过滤
  if (displayFilter.value === 'linked') {
    filtered = filtered.filter(host => host.cmdb_linked)
  } else if (displayFilter.value === 'unlinked') {
    filtered = filtered.filter(host => !host.cmdb_linked)
  }
  // displayFilter.value === 'all' 时不过滤

  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(host =>
      host.hostname.toLowerCase().includes(keyword) ||
      (host.ip_address && host.ip_address.toLowerCase().includes(keyword))
    )
  }

  return filtered
})

// 方法
const refreshData = async () => {
  loading.value.refresh = true
  try {
    console.log('🔄 开始刷新数据')
    await Promise.all([
      loadHostStatus(),
      loadStatistics(),
      loadHostGroups()
    ])
    console.log('✅ 数据刷新完成')
    ElMessage.success('数据刷新完成')
  } catch (error) {
    console.error('❌ 数据刷新失败:', error)
    ElMessage.error('数据刷新失败')
  } finally {
    loading.value.refresh = false
  }
}

// 智能同步命令处理
const handleSyncCommand = async (command: string) => {
  loading.value.sync = true

  try {
    switch (command) {
      case 'auto':
        await autoSync()
        break
      case 'force':
        await forceReassociation()
        break
      case 'cmdb-to-zabbix':
        await syncCMDBToZabbix()
        break
      case 'cleanup':
        await cleanupOrphanedData()
        break
    }
  } finally {
    loading.value.sync = false
  }
}

// 自动同步（推荐操作）
const autoSync = async () => {
  ElMessage.info('开始智能同步...')

  try {
    // TODO: 实现自动同步API调用
    // const response = await monitoringApi.autoSyncHosts({
    //   zabbix_server_id: selectedZabbixServer.value
    // })

    // 临时使用现有的同步逻辑
    await syncHosts()

    ElMessage.success('智能同步完成！')
    await refreshData()
  } catch (error) {
    console.error('自动同步失败:', error)
    ElMessage.error('自动同步失败')
  }
}

// 强制重新关联（原清理数据功能）
const forceReassociation = async () => {
  await cleanupMonitoringData()
}

// CMDB到Zabbix同步（原同步主机功能）
const syncCMDBToZabbix = async () => {
  await syncHosts()
}

// 清理孤立数据
const cleanupOrphanedData = async () => {
  try {
    await ElMessageBox.confirm(
      '此操作将清理所有孤立的监控数据，确定继续吗？',
      '清理孤立数据',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    ElMessage.info('开始清理孤立数据...')

    // TODO: 实现清理孤立数据的API
    // 临时使用现有清理逻辑
    await cleanupMonitoringData()

  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理孤立数据失败:', error)
      ElMessage.error('清理失败')
    }
  }
}

// 显示设置命令处理
const handleDisplayCommand = (command: string) => {
  switch (command) {
    case 'show-all':
      displayFilter.value = 'all'
      showUnlinkedHosts.value = true
      displayMode.value = 'all'
      ElMessage.success('已切换为显示全部主机')
      break
    case 'show-linked':
      displayFilter.value = 'linked'
      showUnlinkedHosts.value = false
      displayMode.value = 'grouped'
      ElMessage.success('已切换为仅显示已关联主机')
      break
    case 'show-unlinked':
      displayFilter.value = 'unlinked'
      showUnlinkedHosts.value = true
      displayMode.value = 'flat'
      ElMessage.success('已切换为仅显示未关联主机')
      break
    case 'auto-refresh':
      showAutoRefreshSettings()
      break
  }
}

// 显示自动刷新设置
const showAutoRefreshSettings = () => {
  autoRefreshDialog.value = true
}

// 显示主机管理对话框
const showHostManagement = () => {
  hostManagementDialog.value = true
}

// 快速关联主机
const quickAssociate = async (host: any) => {
  try {
    ElMessage.info(`正在关联主机 ${host.hostname}...`)

    const response = await monitoringApi.quickAssociateHost({
      zabbix_host_id: host.id || host.zabbix_host_id,
      zabbix_server_id: selectedZabbixServer.value,
      hostname: host.hostname
    })

    if (response.data.success) {
      ElMessage.success(response.data.message)
      await refreshData()
    } else {
      ElMessage.error(response.data.message || '快速关联失败')
    }
  } catch (error) {
    console.error('快速关联失败:', error)
    ElMessage.error('快速关联失败')
  }
}

// 保存自动刷新设置
const saveAutoRefreshSettings = () => {
  // 保存到localStorage
  localStorage.setItem('autoRefreshSettings', JSON.stringify(autoRefreshSettings.value))

  // 重新设置定时器
  setupAutoRefresh()

  autoRefreshDialog.value = false
  ElMessage.success('自动刷新设置已保存')
}

// 设置自动刷新
const setupAutoRefresh = () => {
  // 清除现有定时器
  if (autoRefreshTimer.value) {
    clearInterval(autoRefreshTimer.value)
    autoRefreshTimer.value = null
  }

  // 如果启用自动刷新，设置新定时器
  if (autoRefreshSettings.value.enabled) {
    autoRefreshTimer.value = setInterval(() => {
      if (!autoRefreshSettings.value.onlyWhenVisible || document.visibilityState === 'visible') {
        console.log('🔄 自动刷新数据')
        refreshData()
      }
    }, autoRefreshSettings.value.interval * 1000)

    console.log(`✅ 自动刷新已启用，间隔: ${autoRefreshSettings.value.interval}秒`)
  }
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (autoRefreshTimer.value) {
    clearInterval(autoRefreshTimer.value)
    autoRefreshTimer.value = null
    console.log('🛑 自动刷新已停止')
  }
}

// 获取Zabbix服务器列表
const loadZabbixServers = async () => {
  try {
    console.log('开始加载Zabbix服务器列表...')
    const response = await monitoringApi.getZabbixServers()
    console.log('Zabbix服务器API响应:', response)

    if (response.data.success) {
      zabbixServers.value = response.data.data || []
      console.log('成功加载Zabbix服务器列表:', zabbixServers.value.length, '个服务器')

      // 如果只有一个服务器，自动选择
      if (zabbixServers.value.length === 1) {
        selectedZabbixServer.value = zabbixServers.value[0].id
        console.log('自动选择唯一的Zabbix服务器:', zabbixServers.value[0].name)
      }
    } else {
      console.error('获取Zabbix服务器列表失败:', response.data.message)
      ElMessage.error('获取Zabbix服务器列表失败: ' + response.data.message)
    }
  } catch (error) {
    console.error('获取Zabbix服务器列表异常:', error)
    ElMessage.error('获取Zabbix服务器列表失败')
  }
}

// Zabbix服务器切换处理
const onZabbixServerChange = (serverId: string) => {
  console.log('切换Zabbix服务器:', serverId)
  selectedZabbixServer.value = serverId

  if (serverId) {
    // 清空当前数据
    hosts.value = []
    hostGroups.value = []

    // 重新加载数据
    loadHostStatus()
  }
}

// 简化数据获取 - 移除复杂缓存机制，直接获取实时数据

const loadHostStatus = async () => {
  if (!selectedZabbixServer.value) {
    console.log('未选择Zabbix服务器，跳过加载主机状态')
    return
  }

  try {
    console.log('开始加载主机状态数据，Zabbix服务器ID:', selectedZabbixServer.value)
    const response = await monitoringApi.getHostStatus(selectedZabbixServer.value)
    console.log('主机状态API响应:', response)

    if (response.data.success) {
      // 后端返回的数据结构是 { data: { hosts: [...], statistics: {...} } }
      const responseData = response.data.data
      hosts.value = responseData.hosts || []
      console.log('成功加载主机状态数据:', hosts.value.length, '个主机')

      // 更新统计数据
      const statsData = {
        total_hosts: responseData.statistics?.total || 0,
        online_hosts: responseData.statistics?.online || 0,
        offline_hosts: responseData.statistics?.offline || 0,
        alert_hosts: responseData.statistics?.alert_hosts || 0
      }
      Object.assign(statistics, statsData)
      console.log('更新统计数据:', statistics)

      // 数据加载完成

      // 持久化数据到localStorage，并记录时间戳
      localStorage.setItem('monitoring_hosts', JSON.stringify(hosts.value))
      localStorage.setItem('monitoring_statistics', JSON.stringify(statistics))
      localStorage.setItem('monitoring_cache_timestamp', Date.now().toString())
      console.log('💾 数据已保存到缓存，时间戳:', new Date().toLocaleTimeString())
    } else {
      console.warn('主机状态API返回失败:', response.data)
      // 不显示错误消息，避免死循环
    }
  } catch (error) {
    console.error('加载主机状态失败:', error)
    // 如果API失败，尝试从localStorage恢复数据，但不显示错误消息
    loadFromCache()
  }
}

// 加载主机组数据
const loadHostGroups = async () => {
  try {
    console.log('🔄 开始加载主机组数据...')
    const response = await hostAPI.getHostGroups()
    console.log('📡 主机组API响应:', response)

    if (response.data && response.data.results && Array.isArray(response.data.results)) {
      hostGroups.value = response.data.results
      console.log('✅ 成功加载主机组数据:', hostGroups.value.length, '个主机组')
      console.log('📋 主机组详细数据:', hostGroups.value)

      // 持久化主机组数据
      localStorage.setItem('monitoring_hostgroups', JSON.stringify(hostGroups.value))
    } else {
      console.warn('⚠️ 主机组API返回的数据格式不正确:', response)
      hostGroups.value = []
    }
  } catch (error) {
    console.error('加载主机组失败:', error)
    // 如果API失败，尝试从localStorage恢复数据，但不显示错误消息
    const cachedGroups = localStorage.getItem('monitoring_hostgroups')
    if (cachedGroups) {
      try {
        const parsed = JSON.parse(cachedGroups)
        if (Array.isArray(parsed)) {
          hostGroups.value = parsed
          console.log('从缓存恢复主机组数据:', hostGroups.value.length, '个主机组')
        } else {
          hostGroups.value = []
        }
      } catch (parseError) {
        console.error('解析缓存的主机组数据失败:', parseError)
        hostGroups.value = []
      }
    } else {
      hostGroups.value = []
    }
  }
}

// 从缓存加载数据
const loadFromCache = () => {
  try {
    const cachedHosts = localStorage.getItem('monitoring_hosts')
    const cachedStats = localStorage.getItem('monitoring_statistics')
    const cachedGroups = localStorage.getItem('monitoring_hostgroups')

    // 检查缓存时间戳，如果超过5分钟就不使用缓存
    const cacheTimestamp = localStorage.getItem('monitoring_cache_timestamp')
    const now = Date.now()
    const cacheAge = cacheTimestamp ? now - parseInt(cacheTimestamp) : Infinity
    const maxCacheAge = 5 * 60 * 1000 // 5分钟

    if (cacheAge > maxCacheAge) {
      console.log('📦 缓存已过期，清除旧缓存数据')
      localStorage.removeItem('monitoring_hosts')
      localStorage.removeItem('monitoring_statistics')
      localStorage.removeItem('monitoring_hostgroups')
      localStorage.removeItem('monitoring_cache_timestamp')
      return
    }

    if (cachedHosts && cachedHosts !== 'undefined' && cachedHosts !== 'null') {
      try {
        const parsed = JSON.parse(cachedHosts)
        if (Array.isArray(parsed)) {
          hosts.value = parsed
          console.log('📦 从缓存加载主机数据:', hosts.value.length, '个主机 (缓存年龄:', Math.round(cacheAge/1000), '秒)')
        }
      } catch (e) {
        console.warn('主机缓存数据损坏，清除缓存')
        localStorage.removeItem('monitoring_hosts')
      }
    }

    if (cachedStats && cachedStats !== 'undefined' && cachedStats !== 'null') {
      try {
        Object.assign(statistics, JSON.parse(cachedStats))
        console.log('📦 从缓存加载统计数据')
      } catch (e) {
        console.warn('统计缓存数据损坏，清除缓存')
        localStorage.removeItem('monitoring_statistics')
      }
    }

    if (cachedGroups && cachedGroups !== 'undefined' && cachedGroups !== 'null') {
      try {
        const parsed = JSON.parse(cachedGroups)
        if (Array.isArray(parsed)) {
          hostGroups.value = parsed
          console.log('📦 从缓存加载主机组数据:', hostGroups.value.length, '个主机组')
        } else {
          hostGroups.value = []
        }
      } catch (e) {
        console.warn('主机组缓存数据损坏，清除缓存')
        localStorage.removeItem('monitoring_hostgroups')
        hostGroups.value = []
      }
    } else {
      hostGroups.value = []
    }
  } catch (error) {
    console.error('❌ 从缓存加载数据失败:', error)
    hostGroups.value = []
  }
}

const loadStatistics = async () => {
  try {
    const response = await monitoringApi.getOverview()
    if (response.data.success) {
      Object.assign(statistics, response.data.data)
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    // 不显示错误消息，避免死循环
  }
}

const syncHosts = async () => {
  try {
    // 首先获取可用的Zabbix服务器
    const serversResponse = await monitoringApi.getZabbixServers()
    if (!serversResponse.data.success || !serversResponse.data.data.length) {
      ElMessage.error('没有找到可用的Zabbix服务器')
      return
    }

    // 使用第一个连接的Zabbix服务器
    const connectedServer = serversResponse.data.data.find(server =>
      server.is_active && server.connection_status === 'connected'
    )

    if (!connectedServer) {
      ElMessage.error('没有找到已连接的Zabbix服务器')
      return
    }

    ElMessage.info('开始同步主机数据到Zabbix...')

    // 调用同步API
    const syncResponse = await monitoringApi.syncHostsToZabbix({
      zabbix_server_id: connectedServer.id
    })

    if (syncResponse.data.success) {
      const data = syncResponse.data.data
      ElMessage.success(
        `同步完成！成功: ${data.success_count}, 失败: ${data.error_count}`
      )

      // 刷新数据
      await refreshData()
    } else {
      ElMessage.error(syncResponse.data.message || '同步失败')
    }
  } catch (error) {
    console.error('同步主机失败:', error)
    ElMessage.error('同步主机失败')
  }
}

// 清理监控数据
const cleanupMonitoringData = async () => {
  try {
    await ElMessageBox.confirm(
      '此操作将清理所有旧的监控主机数据并重新建立关联，确定继续吗？',
      '清理监控数据',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    if (!selectedZabbixServer.value) {
      ElMessage.error('请先选择Zabbix服务器')
      return
    }

    ElMessage.info('开始清理监控数据...')

    // 调用清理API
    const response = await monitoringApi.cleanupMonitoringHosts({
      zabbix_server_id: selectedZabbixServer.value
    })

    if (response.data.success) {
      const data = response.data.data
      ElMessage.success(
        `清理完成！删除旧记录: ${data.deleted_old_records}个，重新关联: ${data.matched_hosts}个`
      )

      // 清理前端缓存
      localStorage.clear()

      // 刷新数据
      await refreshData()
    } else {
      ElMessage.error('清理失败: ' + response.data.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理监控数据失败:', error)
      ElMessage.error('清理失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

const getHostStatusFromAvailability = (availability) => {
  switch (availability) {
    case '1': return 'online'
    case '2': return 'offline'
    default: return 'unknown'
  }
}

const getHostStatusClass = (status) => {
  switch (status) {
    case 'online': return 'status-online'
    case 'offline': return 'status-offline'
    default: return 'status-unknown'
  }
}


const getHostStatusIcon = (status) => {
  switch (status) {
    case 'online': return 'fa fa-check-circle text-success'
    case 'offline': return 'fa fa-times-circle text-danger'
    default: return 'fa fa-question-circle text-warning'
  }
}

const getHostStatusText = (status) => {
  switch (status) {
    case 'online': return '在线'
    case 'offline': return '离线'
    default: return '未知'
  }
}

const formatTime = (timeString: Date | string | null | undefined) => {
  if (!timeString) return '未知'
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN')
}

const viewHostDetails = (host) => {
  showHostMetricsDialog(host)
}

const viewHostGraphs = (host) => {
  ElMessage.info(`查看主机图表: ${host.hostname}`)
}

const manageHost = (host) => {
  ElMessage.info(`管理主机: ${host.hostname}`)
}

// 折叠功能方法
const toggleEnvironment = (envKey) => {
  if (collapsedEnvironments.value.has(envKey)) {
    collapsedEnvironments.value.delete(envKey)
  } else {
    collapsedEnvironments.value.add(envKey)
  }
  // 保存折叠状态到localStorage
  localStorage.setItem('collapsed_environments', JSON.stringify([...collapsedEnvironments.value]))
}

const toggleGroup = (groupId) => {
  if (collapsedGroups.value.has(groupId)) {
    collapsedGroups.value.delete(groupId)
  } else {
    collapsedGroups.value.add(groupId)
  }
  // 保存折叠状态到localStorage
  localStorage.setItem('collapsed_groups', JSON.stringify([...collapsedGroups.value]))
}

// 全部展开
const expandAllSections = () => {
  collapsedEnvironments.value.clear()
  collapsedGroups.value.clear()
  localStorage.setItem('collapsed_environments', JSON.stringify([]))
  localStorage.setItem('collapsed_groups', JSON.stringify([]))
  ElMessage.success('已展开所有环境和主机组')
}

// 全部折叠
const collapseAllSections = () => {
  // 获取所有环境和主机组ID
  const allEnvKeys = environments.map(env => env.key)
  const allGroupIds = hostGroups.value ? hostGroups.value.map(group => group.id) : []

  // 添加未分组主机环境
  if (getUngroupedHosts().length > 0) {
    allEnvKeys.push('ungrouped')
  }

  // 确保数据存在
  if (allEnvKeys.length === 0 && allGroupIds.length === 0) {
    ElMessage.warning('暂无可折叠的内容')
    return
  }

  collapsedEnvironments.value = new Set(allEnvKeys)
  collapsedGroups.value = new Set(allGroupIds)

  localStorage.setItem('collapsed_environments', JSON.stringify(allEnvKeys))
  localStorage.setItem('collapsed_groups', JSON.stringify(allGroupIds))
  ElMessage.success('已折叠所有环境和主机组')
}

// 监听筛选条件变化，自动展开相关内容
watch([filterStatus, searchKeyword], ([newFilterStatus, newSearchKeyword], [oldFilterStatus, oldSearchKeyword]) => {
  // 如果有筛选条件（状态筛选或搜索关键词），自动展开所有内容
  if (newFilterStatus || newSearchKeyword) {
    // 检查是否所有内容都被折叠了
    const hasCollapsedContent = collapsedEnvironments.value.size > 0 || collapsedGroups.value.size > 0

    if (hasCollapsedContent) {
      expandAllSections()
      console.log('检测到筛选条件，自动展开所有内容')
    }
  }
})

// 监听Zabbix服务器选择变化，保存到本地存储
watch(selectedZabbixServer, (newServerId) => {
  if (newServerId) {
    localStorage.setItem('selected_zabbix_server', newServerId)
    console.log('保存选择的Zabbix服务器:', newServerId)
  } else {
    localStorage.removeItem('selected_zabbix_server')
  }
})

// 树形结构相关方法
const expandAll = () => {
  const allKeys = []
  const collectKeys = (nodes) => {
    nodes.forEach(node => {
      if (node.type !== 'host') {
        allKeys.push(node.id)
      }
      if (node.children) {
        collectKeys(node.children)
      }
    })
  }
  collectKeys(hostTreeData.value)
  expandedKeys.value = allKeys

  nextTick(() => {
    if (hostTreeRef.value) {
      hostTreeRef.value.setExpandedKeys(expandedKeys.value)
    }
  })
}

const collapseAll = () => {
  expandedKeys.value = []
  nextTick(() => {
    if (hostTreeRef.value) {
      hostTreeRef.value.setExpandedKeys([])
    }
  })
}

const handleNodeClick = (data, node, component) => {
  if (data.type === 'host') {
    // 主机节点：选中主机
    console.log('选中主机:', data)
  } else {
    // 环境或主机组节点：展开/折叠
    console.log('点击节点:', data)
  }
}

const handleNodeExpand = (data, node) => {
  if (!expandedKeys.value.includes(data.id)) {
    expandedKeys.value.push(data.id)
    localStorage.setItem('monitoring_expanded_keys', JSON.stringify(expandedKeys.value))
  }
}

const handleNodeCollapse = (data, node) => {
  const index = expandedKeys.value.indexOf(data.id)
  if (index > -1) {
    expandedKeys.value.splice(index, 1)
    localStorage.setItem('monitoring_expanded_keys', JSON.stringify(expandedKeys.value))
  }
}

const getNodeClass = (data) => {
  return {
    'env-node': data.type === 'environment',
    'group-node': data.type === 'group',
    'host-node': data.type === 'host',
    'host-online': data.type === 'host' && data.availability === 'available',
    'host-offline': data.type === 'host' && data.availability !== 'available'
  }
}

const getNodeIcon = (data) => {
  switch (data.type) {
    case 'environment':
      return 'fa fa-globe'
    case 'group':
      return 'fa fa-folder'
    case 'host':
      return 'fa fa-server'
    default:
      return 'fa fa-circle'
  }
}

// WebSocket消息处理 - 暂时禁用，避免数据冲突
const handleMonitoringUpdate = (data: any) => {
  console.log('🔄 收到WebSocket监控数据更新 (已禁用):', data)

  // 暂时不处理WebSocket数据，只使用API数据
  // 避免WebSocket和API数据结构不一致导致的状态混乱

  // if (data.host_status) {
  //   hosts.value = data.host_status
  //   console.log('✅ WebSocket更新主机数据:', hosts.value.length, '个主机')
  //   localStorage.setItem('monitoring_hosts', JSON.stringify(data.host_status))
  //   localStorage.setItem('monitoring_cache_timestamp', Date.now().toString())
  // }
  // if (data.overview) {
  //   Object.assign(statistics, data.overview)
  //   console.log('✅ WebSocket更新统计数据:', statistics.value)
  //   localStorage.setItem('monitoring_statistics', JSON.stringify(statistics.value))
  // }
}

// 监控数据格式化函数
const formatBytes = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化监控指标值
const formatMetricValue = (value: any, unit: string = '', isBytes: boolean = false): string => {
  if (value === undefined || value === null || value === '') {
    return '暂无数据'
  }

  // 处理负载平均值对象格式 {1m: 0.01, 5m: 0.03, 15m: 0.0}
  if (typeof value === 'object' && value !== null) {
    if (value['1m'] !== undefined || value['5m'] !== undefined || value['15m'] !== undefined) {
      const load1m = value['1m'] !== undefined ? parseFloat(value['1m']).toFixed(2) : '--'
      const load5m = value['5m'] !== undefined ? parseFloat(value['5m']).toFixed(2) : '--'
      const load15m = value['15m'] !== undefined ? parseFloat(value['15m']).toFixed(2) : '--'
      return `${load1m} / ${load5m} / ${load15m}`
    }
    return '暂无数据'
  }

  const numValue = parseFloat(value)
  if (isNaN(numValue)) {
    return '暂无数据'
  }

  if (isBytes) {
    return formatBytes(numValue) + unit
  }

  if (unit === '%') {
    return numValue.toFixed(1) + unit
  }

  return numValue.toFixed(2) + unit
}

// 获取监控指标的CSS类
const getMetricClass = (type: string, value: any): string => {
  if (value === undefined || value === null || value === '') {
    return 'metric-unavailable'
  }

  // 处理负载平均值对象格式
  if (type === 'load' && typeof value === 'object' && value !== null) {
    // 使用1分钟负载作为判断标准
    const load1m = parseFloat(value['1m'])
    if (isNaN(load1m)) {
      return 'metric-unavailable'
    }
    if (load1m >= 2.0) return 'metric-critical'
    if (load1m >= 1.0) return 'metric-warning'
    return 'metric-normal'
  }

  const numValue = parseFloat(value)
  if (isNaN(numValue)) {
    return 'metric-unavailable'
  }

  switch (type) {
    case 'cpu':
    case 'memory':
    case 'disk':
      if (numValue >= 90) return 'metric-critical'
      if (numValue >= 70) return 'metric-warning'
      return 'metric-normal'

    case 'load':
      if (numValue >= 2.0) return 'metric-critical'
      if (numValue >= 1.0) return 'metric-warning'
      return 'metric-normal'

    default:
      return 'metric-normal'
  }
}



// 监控指标样式类
const getCpuUsageClass = (usage: number) => {
  if (usage >= 80) return 'metric-critical'
  if (usage >= 60) return 'metric-warning'
  return 'metric-normal'
}

const getMemoryUsageClass = (usage: number) => {
  if (usage >= 85) return 'metric-critical'
  if (usage >= 70) return 'metric-warning'
  return 'metric-normal'
}

const getDiskUsageClass = (usage: number) => {
  if (usage >= 90) return 'metric-critical'
  if (usage >= 75) return 'metric-warning'
  return 'metric-normal'
}

const getLoadAverageClass = (load: number) => {
  if (load >= 4) return 'metric-critical'
  if (load >= 2) return 'metric-warning'
  return 'metric-normal'
}

// 监控指标弹窗相关方法
const showHostMetricsDialog = async (host: any) => {
  selectedHost.value = host
  metricsDialogVisible.value = true
  await loadHostMetrics(host)
}

const handleCloseMetricsDialog = () => {
  metricsDialogVisible.value = false
  selectedHost.value = null
  hostMetrics.value = {}
}

const loadHostMetrics = async (host: any) => {
  if (!host.zabbix_host_id) {
    ElMessage.warning('该主机未配置Zabbix监控')
    return
  }

  if (!selectedZabbixServer.value) {
    ElMessage.warning('请先选择Zabbix服务器')
    return
  }

  loadingMetrics.value = true
  try {
    const response = await monitoringApi.getHostMetrics(host.zabbix_host_id, selectedZabbixServer.value)
    if (response.data && response.data.success) {
      hostMetrics.value = response.data.data || {}
      console.log('获取到监控指标数据:', hostMetrics.value)
    } else {
      console.error(`获取监控指标失败: ${response.data?.message || '未知错误'}`)
      hostMetrics.value = {}
    }
  } catch (error) {
    console.error('获取主机监控指标失败:', error)
    // 不显示错误消息，避免死循环
    hostMetrics.value = {}
  } finally {
    loadingMetrics.value = false
  }
}

const refreshHostMetrics = async () => {
  if (selectedHost.value) {
    await loadHostMetrics(selectedHost.value)
  }
}

// 分类折叠控制
const toggleCategory = (categoryKey: string) => {
  if (collapsedCategories.value.has(categoryKey)) {
    collapsedCategories.value.delete(categoryKey)
  } else {
    collapsedCategories.value.add(categoryKey)
  }
}

// 获取分类图标
const getCategoryIcon = (categoryKey: string): string => {
  const iconMap: Record<string, string> = {
    'system': 'fa fa-cogs',
    'cpu': 'fa fa-microchip',
    'memory': 'fa fa-memory',
    'disk': 'fa fa-hdd',
    'network': 'fa fa-network-wired',
    'process': 'fa fa-tasks',
    'application': 'fa fa-cube',
    'other': 'fa fa-question-circle'
  }
  return iconMap[categoryKey] || 'fa fa-chart-bar'
}

// 获取监控指标图标（增强版）
const getMetricIcon = (key: string, category?: string): string => {
  const keyLower = key.toLowerCase()

  // 根据分类优先匹配
  if (category === 'cpu') {
    if (keyLower.includes('idle')) return 'fa fa-pause-circle'
    if (keyLower.includes('load')) return 'fa fa-weight-hanging'
    return 'fa fa-microchip'
  }

  if (category === 'memory') {
    if (keyLower.includes('available')) return 'fa fa-memory text-success'
    if (keyLower.includes('used')) return 'fa fa-memory text-warning'
    return 'fa fa-memory'
  }

  if (category === 'disk') {
    if (keyLower.includes('read')) return 'fa fa-arrow-down'
    if (keyLower.includes('write')) return 'fa fa-arrow-up'
    if (keyLower.includes('space') || keyLower.includes('size')) return 'fa fa-hdd'
    return 'fa fa-database'
  }

  if (category === 'network') {
    if (keyLower.includes('in') || keyLower.includes('receive')) return 'fa fa-arrow-down text-info'
    if (keyLower.includes('out') || keyLower.includes('transmit')) return 'fa fa-arrow-up text-info'
    return 'fa fa-network-wired'
  }

  // 通用匹配
  if (keyLower.includes('cpu')) return 'fa fa-microchip'
  if (keyLower.includes('memory') || keyLower.includes('mem')) return 'fa fa-memory'
  if (keyLower.includes('disk') || keyLower.includes('fs')) return 'fa fa-hdd'
  if (keyLower.includes('network') || keyLower.includes('net')) return 'fa fa-network-wired'
  if (keyLower.includes('process') || keyLower.includes('proc')) return 'fa fa-tasks'
  if (keyLower.includes('uptime')) return 'fa fa-clock'
  if (keyLower.includes('load')) return 'fa fa-weight-hanging'

  return 'fa fa-chart-line'
}

// 获取监控指标值的样式类
const getMetricValueClass = (value: string, key: string, category?: string): string => {
  // 尝试提取数值进行判断
  const numMatch = value.match(/(\d+\.?\d*)/)
  if (!numMatch) return 'metric-normal'

  const numValue = parseFloat(numMatch[1])
  const keyLower = key.toLowerCase()

  // 百分比类型的指标
  if (value.includes('%')) {
    if (numValue >= 90) return 'metric-critical'
    if (numValue >= 75) return 'metric-warning'
    return 'metric-normal'
  }

  // CPU负载
  if (keyLower.includes('load') && category === 'cpu') {
    if (numValue >= 4) return 'metric-critical'
    if (numValue >= 2) return 'metric-warning'
    return 'metric-normal'
  }

  // 默认正常状态
  return 'metric-normal'
}



// 生命周期
onMounted(async () => {
  console.log('🚀 ZabbixHosts页面开始初始化...')

  // 立即显示缓存数据，提供快速响应
  loadFromCache()

  // 恢复UI状态（同步操作，很快）
  const savedExpandedKeys = localStorage.getItem('monitoring_expanded_keys')
  if (savedExpandedKeys) {
    expandedKeys.value = JSON.parse(savedExpandedKeys)
  }

  const savedCollapsedEnvironments = localStorage.getItem('collapsed_environments')
  if (savedCollapsedEnvironments) {
    collapsedEnvironments.value = new Set(JSON.parse(savedCollapsedEnvironments))
  }

  const savedCollapsedGroups = localStorage.getItem('collapsed_groups')
  if (savedCollapsedGroups) {
    collapsedGroups.value = new Set(JSON.parse(savedCollapsedGroups))
  }

  // 加载自动刷新设置
  const savedAutoRefreshSettings = localStorage.getItem('autoRefreshSettings')
  if (savedAutoRefreshSettings) {
    autoRefreshSettings.value = { ...autoRefreshSettings.value, ...JSON.parse(savedAutoRefreshSettings) }
  }

  // 异步加载Zabbix服务器列表（不阻塞页面显示）
  loadZabbixServers().then(() => {
    // 恢复上次选择的Zabbix服务器
    const savedZabbixServer = localStorage.getItem('selected_zabbix_server')
    if (savedZabbixServer && zabbixServers.value.find(s => s.id === savedZabbixServer)) {
      selectedZabbixServer.value = savedZabbixServer
    }

    // 然后异步加载数据
    refreshData().then(() => {
      // 数据加载完成后设置自动刷新
      setupAutoRefresh()
    }).catch(error => {
      console.error('初始数据加载失败:', error)
    })
  })

  // 异步注册WebSocket（不阻塞页面）
  setTimeout(() => {
    monitoringWebSocket.on('monitoring_update', handleMonitoringUpdate)
    monitoringWebSocket.on('initial_data', handleMonitoringUpdate)

    // 连接WebSocket
    if (!monitoringWebSocket.isConnected) {
      monitoringWebSocket.connect().catch(error => {
        console.error('WebSocket连接失败:', error)
      })
    }
  }, 100)

  console.log('✅ ZabbixHosts页面初始化完成（数据异步加载中...）')
})

// 环境定义
const environments = [
  { key: 'dev', name: '开发环境' },
  { key: 'test', name: '测试环境' },
  { key: 'staging', name: '预发布环境' },
  { key: 'prod', name: '生产环境' }
]

// 按环境获取主机组
const getGroupsByEnvironment = (envKey: string) => {
  return hostGroups.value.filter(group => group.environment === envKey)
}

// 获取未分组主机（未关联到CMDB的主机）
const getUngroupedHosts = () => {
  // 只返回未关联到CMDB的主机
  const ungrouped = hosts.value.filter(host => !host.cmdb_linked);

  console.log('未分组主机调试信息:')
  console.log('hosts.value.length:', hosts.value.length)
  console.log('showUnlinkedHosts.value:', showUnlinkedHosts.value)
  console.log('ungrouped.length:', ungrouped.length)
  console.log('ungrouped hosts:', ungrouped.map(h => h.hostname))

  return ungrouped
}

// 按主机组获取主机
const getHostsByGroup = (groupId: number) => {
  return visibleHosts.value.filter(host => {
    // 检查主机是否属于指定的主机组
    if (host.host_groups && Array.isArray(host.host_groups)) {
      return host.host_groups.some(g => g.id === groupId)
    }
    // 如果没有host_groups字段，检查hostData中的主机组信息
    if (host.hostData && host.hostData.host_groups) {
      return host.hostData.host_groups.some(g => g.id === groupId)
    }
    // 如果都没有，根据主机名或IP匹配主机组
    const hostGroup = hostGroups.value.find(g => g.id === groupId)
    if (hostGroup && hostGroup.hosts) {
      return hostGroup.hosts.some(h => h.hostname === host.hostname || h.ip_address === host.ip_address)
    }
    return false
  })
}

// 按环境获取主机
const getHostsByEnvironment = (envKey: string) => {
  // 先获取该环境下的所有主机组
  const envGroups = getGroupsByEnvironment(envKey)
  const envGroupIds = envGroups.map(g => g.id)

  return visibleHosts.value.filter(host => {
    // 检查主机是否属于该环境的任何主机组
    if (host.host_groups && Array.isArray(host.host_groups)) {
      return host.host_groups.some(g => envGroupIds.includes(g.id))
    }
    // 如果没有host_groups字段，检查hostData中的主机组信息
    if (host.hostData && host.hostData.host_groups) {
      return host.hostData.host_groups.some(g => envGroupIds.includes(g.id))
    }
    // 如果都没有，根据主机名或IP在环境的主机组中查找
    return envGroups.some(group => {
      if (group.hosts) {
        return group.hosts.some(h => h.hostname === host.hostname || h.ip_address === host.ip_address)
      }
      return false
    })
  })
}

// 获取环境在线主机数
const getEnvOnlineCount = (envKey: string) => {
  return getHostsByEnvironment(envKey).filter(host =>
    getHostStatusFromAvailability(host.availability) === 'online'
  ).length
}

// 获取环境总主机数
const getEnvTotalCount = (envKey: string) => {
  return getHostsByEnvironment(envKey).length
}

// 获取主机组在线主机数
const getGroupOnlineCount = (groupId: number) => {
  return getHostsByGroup(groupId).filter(host =>
    getHostStatusFromAvailability(host.availability) === 'online'
  ).length
}

// 获取主机组离线主机数
const getGroupOfflineCount = (groupId: number) => {
  return getHostsByGroup(groupId).filter(host =>
    getHostStatusFromAvailability(host.availability) === 'offline'
  ).length
}

// 获取主机组总主机数
const getGroupTotalCount = (groupId: number) => {
  return getHostsByGroup(groupId).length
}

// 获取主机卡片样式类
const getHostCardClass = (status: string) => {
  return {
    'host-card-online': status === 'online',
    'host-card-offline': status === 'offline',
    'host-card-unknown': status === 'unknown'
  }
}

// 主机操作方法
const connectToHost = async (host) => {
  try {
    // 检查主机是否关联了CMDB主机
    if (!host.cmdb_host_id) {
      ElMessage.warning('该主机未关联CMDB主机，无法进行SSH连接')
      return
    }

    // 请求SSH访问令牌
    const response = await axios.post('/api/ssh/request-access/', {
      host_id: host.cmdb_host_id
    })

    if (response.data.success) {
      // 使用访问令牌跳转到SSH页面
      router.push(`/ssh/${host.cmdb_host_id}?token=${response.data.access_token}`)
    } else {
      ElMessage.error(response.data.message || '无权访问此主机')
    }
  } catch (error) {
    console.error('请求SSH访问失败:', error)
    ElMessage.error('请求SSH访问失败，请检查权限')
  }
}

const configureHost = (host) => {
  console.log('配置主机:', host)
  selectedHost.value = host
  configDialogVisible.value = true
  // 只加载基本配置，其他数据懒加载
  loadBasicHostConfiguration(host)
}

// 配置弹窗相关变量
const activeConfigTab = ref('basic')

// 只加载基本主机配置信息（快速打开对话框）
const loadBasicHostConfiguration = async (host) => {
  if (!host.zabbix_host_id || !selectedZabbixServer.value) {
    ElMessage.warning('主机未配置Zabbix监控或未选择Zabbix服务器')
    return
  }

  configLoading.value = true
  try {
    console.log('加载主机基本配置:', host.zabbix_host_id)

    // 获取主机详细信息
    const response = await monitoringApi.getHostConfiguration(host.zabbix_host_id, selectedZabbixServer.value)
    if (response.data.success) {
      const config = response.data.data
      hostConfig.value = {
        basic: {
          host: config.host || '',
          name: config.name || '',
          description: config.description || '',
          status: config.status || 0
        },
        templates: config.templates || [],
        hostgroups: config.hostgroups || [],
        interfaces: config.interfaces || [],
        macros: config.macros || []
      }
    } else {
      ElMessage.error('获取主机配置失败: ' + response.data.message)
    }
  } catch (error) {
    console.error('加载主机配置失败:', error)
    ElMessage.error('加载主机配置失败')
  } finally {
    configLoading.value = false
  }
}



// 防抖标志
const isLoadingTabData = ref(false)

// 处理配置tab切换（懒加载）
const handleConfigTabClick = (tab) => {
  const tabName = tab.props.name
  console.log('=== 切换到tab:', tabName, '===')
  console.log('当前防抖状态:', isLoadingTabData.value)
  console.log('模板数量:', availableTemplates.value.length)
  console.log('主机组数量:', availableHostgroups.value.length)
  console.log('监控项数量:', hostItems.value.length)

  // 防止重复加载
  if (isLoadingTabData.value) {
    console.log('正在加载数据，跳过重复请求')
    return
  }

  // 根据不同tab加载不同数据
  if (tabName === 'templates' && availableTemplates.value.length === 0) {
    console.log('开始加载模板数据')
    loadAvailableTemplates()
  } else if (tabName === 'hostgroups' && availableHostgroups.value.length === 0) {
    console.log('开始加载主机组数据')
    loadAvailableHostgroups()
  } else if (tabName === 'items' && hostItems.value.length === 0) {
    console.log('开始加载监控项数据')
    loadHostItemsForTab(1, itemsSearchText.value)
  } else {
    console.log('无需加载数据，条件不满足')
  }
}

// 单独加载模板
const loadAvailableTemplates = async () => {
  try {
    const response = await monitoringApi.getAvailableTemplates(selectedZabbixServer.value)
    if (response.data.success) {
      availableTemplates.value = response.data.data || []
    }
  } catch (error) {
    console.error('加载可用模板失败:', error)
  }
}

// 单独加载主机组
const loadAvailableHostgroups = async () => {
  try {
    const response = await monitoringApi.getAvailableHostgroups(selectedZabbixServer.value)
    if (response.data.success) {
      availableHostgroups.value = response.data.data || []
    }
  } catch (error) {
    console.error('加载可用主机组失败:', error)
  }
}

// 为tab加载监控项（使用服务端分页）
const loadHostItemsForTab = async (page = 1, search = '') => {
  if (!selectedHost.value?.zabbix_host_id || !selectedZabbixServer.value) return

  if (itemsLoading.value) {
    console.log('正在加载监控项数据，跳过重复请求')
    return
  }

  itemsLoading.value = true
  try {
    console.log('为tab加载主机监控项:', selectedHost.value.zabbix_host_id, '页码:', page, '搜索:', search)
    const response = await monitoringApi.getHostItems(
      selectedHost.value.zabbix_host_id,
      selectedZabbixServer.value,
      page,
      itemsPageSize.value,
      search
    )
    console.log('后端响应数据:', response.data)
    if (response.data.success) {
      const data = response.data.data
      console.log('解析的数据结构:', data)
      hostItems.value = data.items || []
      itemsTotal.value = data.total || 0
      itemsCurrentPage.value = data.page || 1

      // 数据加载完成

      console.log('加载到监控项:', hostItems.value.length, '个，总计:', itemsTotal.value)
    } else {
      console.error('获取监控项失败:', response.data.message)
      hostItems.value = []
      itemsTotal.value = 0
    }
  } catch (error) {
    console.error('加载监控项失败:', error)
    hostItems.value = []
    itemsTotal.value = 0
  } finally {
    itemsLoading.value = false
  }
}

// 处理监控项分页变化
const handleItemsPageChange = (page: number) => {
  console.log('监控项分页变化:', page)
  loadHostItemsForTab(page, itemsSearchText.value)
}

// 处理监控项每页大小变化
const handleItemsPageSizeChange = (pageSize: number) => {
  console.log('监控项每页大小变化:', pageSize)
  itemsPageSize.value = pageSize
  itemsCurrentPage.value = 1
  loadHostItemsForTab(1, itemsSearchText.value)
}

// 搜索防抖定时器
let searchTimer: NodeJS.Timeout | null = null

// 处理监控项搜索
const handleItemsSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    console.log('监控项搜索:', itemsSearchText.value)
    itemsCurrentPage.value = 1
    loadHostItemsForTab(1, itemsSearchText.value)
  }, 500) // 500ms防抖
}

// 处理搜索清空
const handleItemsSearchClear = () => {
  console.log('清空监控项搜索')
  itemsCurrentPage.value = 1
  loadHostItemsForTab(1, '')
}

// 切换监控项状态
const toggleItemStatus = async (item) => {
  const newStatus = item.status === 0 ? 1 : 0
  const originalStatus = item.status

  // 先更新UI状态，提供即时反馈
  item.status = newStatus

  try {
    const response = await monitoringApi.updateItemStatus(item.itemid, newStatus, selectedZabbixServer.value)
    if (response.data.success) {
      ElMessage.success(`监控项已${newStatus === 0 ? '启用' : '禁用'}`)
    } else {
      // 恢复到原始状态
      item.status = originalStatus
      ElMessage.error('更新监控项状态失败: ' + response.data.message)
    }
  } catch (error) {
    console.error('更新监控项状态失败:', error)
    // 恢复到原始状态
    item.status = originalStatus
    ElMessage.error('更新监控项状态失败')
  }
}

// 删除自定义监控项
const deleteCustomItem = (item) => {
  ElMessageBox.confirm(
    `确定要删除监控项 "${item.name}" 吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'glass-message-box'
    }
  ).then(async () => {
    try {
      const response = await monitoringApi.deleteItem(item.itemid, selectedZabbixServer.value)
      if (response.data.success) {
        ElMessage.success('监控项删除成功')
        // 重新加载监控项列表
        loadHostItemsForTab(itemsCurrentPage.value, itemsSearchText.value)
      } else {
        ElMessage.error('删除监控项失败: ' + response.data.message)
      }
    } catch (error) {
      console.error('删除监控项失败:', error)
      ElMessage.error('删除监控项失败')
    }
  }).catch(() => {})
}

// 加载可用的模板和主机组选项
const loadAvailableOptions = async () => {
  try {
    // 获取可用模板
    const templatesResponse = await monitoringApi.getAvailableTemplates(selectedZabbixServer.value)
    if (templatesResponse.data.success) {
      availableTemplates.value = templatesResponse.data.data || []
    }

    // 获取可用主机组
    const hostgroupsResponse = await monitoringApi.getAvailableHostgroups(selectedZabbixServer.value)
    if (hostgroupsResponse.data.success) {
      availableHostgroups.value = hostgroupsResponse.data.data || []
    }
  } catch (error) {
    console.error('加载可用选项失败:', error)
  }
}

// 关闭配置弹窗
const handleCloseConfigDialog = () => {
  configDialogVisible.value = false
  activeConfigTab.value = 'basic'
  selectedHost.value = null

  // 清理所有数据
  hostConfig.value = {
    basic: { host: '', name: '', description: '', status: 0 },
    templates: [],
    hostgroups: [],
    interfaces: [],
    macros: []
  }

  // 清理懒加载的数据
  availableTemplates.value = []
  availableHostgroups.value = []
  hostItems.value = []
  templateSearchText.value = ''

  // 重置防抖标志
  isLoadingTabData.value = false

  // 重置分页状态
  itemsCurrentPage.value = 1
  itemsTotal.value = 0
  itemsSearchText.value = ''
  itemsLoading.value = false
  hostgroupSearchText.value = ''
  selectedTemplateToAdd.value = ''
  selectedHostgroupToAdd.value = ''
}

// 保存主机配置
const saveHostConfiguration = async () => {
  if (!selectedHost.value?.zabbix_host_id || !selectedZabbixServer.value) {
    ElMessage.warning('无效的主机信息')
    return
  }

  configLoading.value = true
  try {
    const response = await monitoringApi.updateHostConfiguration(
      selectedHost.value.zabbix_host_id,
      hostConfig.value,
      selectedZabbixServer.value
    )

    if (response.data.success) {
      ElMessage.success('主机配置保存成功')
      handleCloseConfigDialog()
      // 刷新主机列表
      loadHostStatus()
    } else {
      ElMessage.error('保存配置失败: ' + response.data.message)
    }
  } catch (error) {
    console.error('保存配置失败:', error)
    ElMessage.error('保存配置失败')
  } finally {
    configLoading.value = false
  }
}

// 添加选中的模板
const addSelectedTemplate = () => {
  if (!selectedTemplateToAdd.value) {
    ElMessage.warning('请选择要添加的模板')
    return
  }

  const template = availableTemplates.value.find(t => t.templateid === selectedTemplateToAdd.value)
  if (template) {
    // 检查是否已经添加过该模板
    const exists = hostConfig.value.templates.find(t => t.templateid === template.templateid)
    if (exists) {
      ElMessage.warning(`模板 "${template.name}" 已经添加过了`)
      return
    }

    hostConfig.value.templates.push(template)
    ElMessage.success(`已添加模板: ${template.name}`)
    selectedTemplateToAdd.value = '' // 清空选择
  }
}

// 移除模板
const removeTemplate = (template) => {
  ElMessageBox.confirm(`确定要移除模板 "${template.name}" 吗？`, '确认移除', {
    confirmButtonText: '移除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = hostConfig.value.templates.findIndex(t => t.templateid === template.templateid)
    if (index > -1) {
      hostConfig.value.templates.splice(index, 1)
      ElMessage.success(`已移除模板: ${template.name}`)
    }
  }).catch(() => {})
}

// 添加选中的主机组
const addSelectedHostgroup = () => {
  if (!selectedHostgroupToAdd.value) {
    ElMessage.warning('请选择要添加的主机组')
    return
  }

  const group = availableHostgroups.value.find(g => g.groupid === selectedHostgroupToAdd.value)
  if (group) {
    // 检查是否已经添加过该主机组
    const exists = hostConfig.value.hostgroups.find(g => g.groupid === group.groupid)
    if (exists) {
      ElMessage.warning(`主机组 "${group.name}" 已经添加过了`)
      return
    }

    hostConfig.value.hostgroups.push(group)
    ElMessage.success(`已添加主机组: ${group.name}`)
    selectedHostgroupToAdd.value = '' // 清空选择
  }
}

// 移除主机组
const removeHostgroup = (group) => {
  ElMessageBox.confirm(`确定要从主机组 "${group.name}" 中移除该主机吗？`, '确认移除', {
    confirmButtonText: '移除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = hostConfig.value.hostgroups.findIndex(g => g.groupid === group.groupid)
    if (index > -1) {
      hostConfig.value.hostgroups.splice(index, 1)
      ElMessage.success(`已从主机组移除: ${group.name}`)
    }
  }).catch(() => {})
}

// 接口管理功能
const addInterface = () => {
  // 显示接口类型选择对话框
  ElMessageBox({
    title: '选择接口类型',
    message: h('div', { style: 'padding: 20px;' }, [
      h('div', { style: 'margin-bottom: 15px; font-weight: bold;' }, '请选择要添加的接口类型：'),
      h('div', { style: 'display: flex; flex-direction: column; gap: 10px;' }, [
        h('button', {
          style: 'padding: 10px; border: 1px solid #409eff; background: rgba(64, 158, 255, 0.1); color: #409eff; border-radius: 4px; cursor: pointer;',
          onClick: () => addInterfaceType('1')
        }, '🖥️ Zabbix Agent (端口: 10050)'),
        h('button', {
          style: 'padding: 10px; border: 1px solid #e6a23c; background: rgba(230, 162, 60, 0.1); color: #e6a23c; border-radius: 4px; cursor: pointer;',
          onClick: () => addInterfaceType('2')
        }, '📡 SNMP (端口: 161)'),
        h('button', {
          style: 'padding: 10px; border: 1px solid #f56c6c; background: rgba(245, 108, 108, 0.1); color: #f56c6c; border-radius: 4px; cursor: pointer;',
          onClick: () => addInterfaceType('3')
        }, '🔧 IPMI (端口: 623)'),
        h('button', {
          style: 'padding: 10px; border: 1px solid #909399; background: rgba(144, 147, 153, 0.1); color: #909399; border-radius: 4px; cursor: pointer;',
          onClick: () => addInterfaceType('4')
        }, '☕ JMX (端口: 12345)')
      ])
    ]),
    showCancelButton: true,
    cancelButtonText: '取消',
    showConfirmButton: false,
    customClass: 'interface-type-dialog'
  }).catch(() => {})
}

const addInterfaceType = (type) => {
  ElMessageBox.close()

  const interfaceTypes = {
    '1': { name: 'Zabbix Agent', port: '10050' },
    '2': { name: 'SNMP', port: '161' },
    '3': { name: 'IPMI', port: '623' },
    '4': { name: 'JMX', port: '12345' }
  }

  const typeInfo = interfaceTypes[type]
  const newInterface = {
    type: type,
    main: hostConfig.value.interfaces.filter(i => i.type === type).length === 0 ? '1' : '0',
    useip: '1',
    ip: '127.0.0.1',
    dns: '',
    port: typeInfo.port
  }

  hostConfig.value.interfaces.push(newInterface)
  ElMessage.success(`已添加${typeInfo.name}接口`)
}

const getDefaultPort = (type) => {
  const ports = {
    '1': '10050',  // Zabbix Agent
    '2': '161',    // SNMP
    '3': '623',    // IPMI
    '4': '12345'   // JMX
  }
  return ports[type] || '10050'
}

const editInterface = (interfaceData, index) => {
  editingInterface.value = { ...interfaceData, index }

  // 填充表单数据
  interfaceForm.value = {
    type: interfaceData.type || '1',
    main: interfaceData.main || '0',
    useip: interfaceData.useip || '1',
    ip: interfaceData.ip || '',
    dns: interfaceData.dns || '',
    port: interfaceData.port || getDefaultPort(interfaceData.type)
  }

  showInterfaceDialog.value = true
}

const saveInterfaceEdit = () => {
  if (!editingInterface.value) return

  const index = editingInterface.value.index
  if (index >= 0 && index < hostConfig.value.interfaces.length) {
    // 更新接口数据
    Object.assign(hostConfig.value.interfaces[index], interfaceForm.value)
    ElMessage.success('接口配置已更新')
  }

  // 关闭对话框
  showInterfaceDialog.value = false
  editingInterface.value = null
}

const cancelInterfaceEdit = () => {
  showInterfaceDialog.value = false
  editingInterface.value = null
}

// 监听接口类型变化，自动更新端口
watch(() => interfaceForm.value.type, (newType) => {
  if (newType) {
    interfaceForm.value.port = getDefaultPort(newType)
  }
})

const removeInterface = (index) => {
  ElMessageBox.confirm('确定要删除这个接口吗？', '确认删除', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    hostConfig.value.interfaces.splice(index, 1)
    ElMessage.success('接口已删除')
  }).catch(() => {})
}

// 宏变量管理功能
const addMacro = () => {
  ElMessageBox.prompt('请输入宏变量名称（如：{$MACRO_NAME}）', '添加宏变量', {
    confirmButtonText: '下一步',
    cancelButtonText: '取消',
    inputPattern: /^\{\$[A-Z0-9_]+\}$/,
    inputErrorMessage: '宏变量名称格式不正确，应为 {$MACRO_NAME} 格式'
  }).then(({ value }) => {
    ElMessageBox.prompt('请输入宏变量值', '设置宏变量值', {
      confirmButtonText: '添加',
      cancelButtonText: '取消'
    }).then(({ value: macroValue }) => {
      const newMacro = {
        macro: value,
        value: macroValue,
        description: ''
      }

      hostConfig.value.macros.push(newMacro)
      ElMessage.success(`已添加宏变量: ${value}`)
    }).catch(() => {})
  }).catch(() => {})
}

const editMacro = (macro, index) => {
  editingMacro.value = { ...macro, index }
  ElMessage.info('宏变量编辑功能开发中...')
}

const removeMacro = (index) => {
  ElMessageBox.confirm('确定要删除这个宏变量吗？', '确认删除', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const macro = hostConfig.value.macros[index]
    hostConfig.value.macros.splice(index, 1)
    ElMessage.success(`已删除宏变量: ${macro.macro}`)
  }).catch(() => {})
}

// 加载主机监控项
const loadHostItems = async (hostId) => {
  if (!hostId || !selectedZabbixServer.value) return

  try {
    console.log('加载主机监控项:', hostId)
    const response = await monitoringApi.getHostItems(hostId, selectedZabbixServer.value)
    if (response.data.success) {
      // 后端API总是返回分页格式的数据结构
      const data = response.data.data
      hostItems.value = data.items || []
      itemsTotal.value = data.total || 0
      console.log('加载到监控项:', hostItems.value.length, '个，总计:', itemsTotal.value)
    } else {
      console.error('获取监控项失败:', response.data.message)
      hostItems.value = []
      itemsTotal.value = 0
    }
  } catch (error) {
    console.error('加载监控项失败:', error)
    hostItems.value = []
    itemsTotal.value = 0
    // 不显示错误消息，避免死循环
  }
}



const viewItemDetails = (item) => {
  ElMessageBox.alert(`
    <div style="text-align: left;">
      <h4>监控项详情</h4>
      <p><strong>名称:</strong> ${item.name}</p>
      <p><strong>键值:</strong> ${item.key_}</p>
      <p><strong>类型:</strong> ${getItemTypeName(item.type)}</p>
      <p><strong>状态:</strong> ${item.status === 0 ? '启用' : '禁用'}</p>
      <p><strong>更新间隔:</strong> ${item.delay || '默认'}</p>
      <p><strong>历史保存:</strong> ${item.history || '默认'}</p>
      <p><strong>趋势保存:</strong> ${item.trends || '默认'}</p>
      ${item.description ? `<p><strong>描述:</strong> ${item.description}</p>` : ''}
    </div>
  `, '监控项详情', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '关闭'
  })
}

// 确认添加监控项
const confirmAddItem = async () => {
  if (!selectedItemTemplate.value) {
    ElMessage.warning('请选择要添加的监控项模板')
    return
  }

  addingItem.value = true
  try {
    // 这里应该调用添加监控项的API
    ElMessage.success('监控项添加成功')
    addItemDialogVisible.value = false
    selectedItemTemplate.value = ''
    // 刷新监控项列表
    if (selectedHost.value) {
      await loadHostItems(selectedHost.value.zabbix_host_id)
    }
  } catch (error) {
    console.error('添加监控项失败:', error)
    ElMessage.error('添加监控项失败')
  } finally {
    addingItem.value = false
  }
}

// 添加调试方法
const debugData = () => {
  console.log('=== 调试数据 ===')
  console.log('hostGroups:', hostGroups.value)
  console.log('hosts:', hosts.value)
  console.log('statistics:', statistics.value)
  console.log('filteredHosts:', filteredHosts.value)
  console.log('environments:', environments)

  // 详细检查第一个主机的数据结构
  if (hosts.value.length > 0) {
    console.log('=== 第一个主机详细数据 ===')
    const firstHost = hosts.value[0]
    console.log('主机对象:', firstHost)
    console.log('主机名:', firstHost.hostname)
    console.log('IP地址:', firstHost.ip_address)
    console.log('可用性:', firstHost.availability)
    console.log('状态:', getHostStatusFromAvailability(firstHost.availability))
    console.log('CPU使用率:', firstHost.cpu_usage)
    console.log('内存使用率:', firstHost.memory_usage)
    console.log('磁盘使用率:', firstHost.disk_usage)
    console.log('网络入流量:', firstHost.network_in)
    console.log('网络出流量:', firstHost.network_out)
    console.log('系统负载:', firstHost.load_average)
    console.log('主机组:', firstHost.host_groups)
    console.log('主机数据:', firstHost.hostData)
  }

  // 检查主机组数据
  if (hostGroups.value.length > 0) {
    console.log('=== 第一个主机组详细数据 ===')
    const firstGroup = hostGroups.value[0]
    console.log('主机组对象:', firstGroup)
    console.log('主机组名称:', firstGroup.name)
    console.log('环境:', firstGroup.environment)
    console.log('主机列表:', firstGroup.hosts)
  }
}

// 组件挂载时初始化
onMounted(async () => {
  console.log('ZabbixHosts组件已挂载')
  await loadZabbixServers()

  // 如果有选中的Zabbix服务器，自动加载主机数据
  if (selectedZabbixServer.value) {
    console.log('自动加载主机数据，服务器ID:', selectedZabbixServer.value)
    await loadHostsData()
  }
})

// 在 <script setup> 中，所有变量和函数都会自动暴露给模板，不需要 return 语句

onUnmounted(() => {
  // 停止自动刷新
  stopAutoRefresh()

  // 清理WebSocket监听器
  monitoringWebSocket.off('monitoring_update', handleMonitoringUpdate)
  monitoringWebSocket.off('initial_data', handleMonitoringUpdate)
})
</script>

<style scoped>
/* 使用与其他页面相同的样式 */
.ansible-audit-container {
  min-height: 100vh;
  background: linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 40, 0.95) 50%, rgba(0, 0, 0, 0.9) 100%);
  overflow-x: hidden;
}

/* 通用可点击样式 */
.clickable {
  user-select: none;
}

.clickable:active {
  transform: scale(0.98);
}

.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  pointer-events: none;
}

.stars, .stars2, .stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent;
}

.stars {
  background-image:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: zoom 20s infinite;
  opacity: 0.6;
}

.stars2 {
  background-image:
    radial-gradient(1px 1px at 40px 60px, #fff, transparent),
    radial-gradient(1px 1px at 120px 25px, rgba(255,255,255,0.9), transparent);
  background-repeat: repeat;
  background-size: 300px 150px;
  animation: zoom 40s infinite;
  opacity: 0.4;
}

.stars3 {
  background-image:
    radial-gradient(1px 1px at 10px 10px, #fff, transparent),
    radial-gradient(1px 1px at 150px 150px, rgba(255,255,255,0.7), transparent);
  background-repeat: repeat;
  background-size: 400px 200px;
  animation: zoom 60s infinite;
  opacity: 0.3;
}

@keyframes zoom {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

.content-wrapper {
  position: relative;
  z-index: 1;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.glass-effect {
  background: rgba(164, 244, 186, 0.05);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  box-shadow:
    0 4px 16px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

.page-header {
  padding: 24px;
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section h1 {
  color: #00eaff;
  margin: 0 0 8px 0;
  font-size: 2rem;
  font-weight: 600;
}

.title-section p {
  color: rgba(255, 255, 255, 0.7);
  margin: 0;
  font-size: 1rem;
}

.action-section {
  display: flex;
  gap: 12px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(164, 244, 186, 0.2);
  color: #00eaff;
  font-size: 1.5rem;
}

.stat-icon.online {
  background: rgba(34, 197, 94, 0.2);
  color: #22c55e;
}

.stat-icon.offline {
  background: rgba(239, 68, 68, 0.2);
  color: #ef4444;
}

.stat-icon.warning {
  background: rgba(245, 158, 11, 0.2);
  color: #f59e0b;
}

.stat-value {
  font-size: 2rem;
  font-weight: bold;
  color: rgba(255, 255, 255, 0.9);
  line-height: 1;
}

.stat-label {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.9rem;
  margin-top: 4px;
}

.hosts-section {
  padding: 24px;
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  color: #00eaff;
  margin: 0;
  font-size: 1.3rem;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.collapse-controls {
  display: flex;
  gap: 8px;
  margin-right: 10px;
}

.collapse-controls .glass-button {
  padding: 8px 12px;
  font-size: 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.expand-button {
  background: rgba(34, 197, 94, 0.1);
  border: 1px solid rgba(34, 197, 94, 0.3);
  color: #22c55e;
}

.expand-button:hover {
  background: rgba(34, 197, 94, 0.2);
  border-color: rgba(34, 197, 94, 0.5);
}

.collapse-button {
  background: rgba(239, 68, 68, 0.1);
  border: 1px solid rgba(239, 68, 68, 0.3);
  color: #ef4444;
}

.collapse-button:hover {
  background: rgba(239, 68, 68, 0.2);
  border-color: rgba(239, 68, 68, 0.5);
}

/* 树形容器样式 */
.hosts-tree-container {
  margin-top: 20px;
  padding: 20px;
  border-radius: 12px;
  background: rgba(164, 244, 186, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(164, 244, 186, 0.2);
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(164, 244, 186, 0.2);
}

.tree-header h3 {
  color: #a4f4ba;
  font-size: 18px;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.tree-controls {
  display: flex;
  gap: 10px;
}

.tree-controls .glass-button {
  padding: 8px 16px;
  font-size: 12px;
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.3);
  color: #a4f4ba;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.tree-controls .glass-button:hover {
  background: rgba(164, 244, 186, 0.2);
  border-color: rgba(164, 244, 186, 0.5);
}

/* 主机监控树样式 */
.host-monitoring-tree {
  background: transparent;
}

.host-monitoring-tree :deep(.el-tree-node__content) {
  background: transparent;
  border: none;
  height: auto;
  min-height: 40px;
  padding: 8px 0;
}

.host-monitoring-tree :deep(.el-tree-node__content:hover) {
  background: rgba(164, 244, 186, 0.1);
}

.tree-node {
  width: 100%;
  display: flex;
  align-items: center;
}

.node-content {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 12px;
}

.node-content i {
  color: #a4f4ba;
  font-size: 16px;
  width: 20px;
  text-align: center;
}

.node-label {
  color: #ffffff;
  font-size: 14px;
  font-weight: 500;
}

/* 环境节点样式 */
.env-node .node-label {
  font-size: 16px;
  font-weight: 600;
  color: #a4f4ba;
}

.env-stats {
  display: flex;
  gap: 15px;
  margin-left: auto;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #ffffff;
  background: rgba(164, 244, 186, 0.1);
  padding: 4px 8px;
  border-radius: 4px;
}

.stat-item.online {
  color: #67c23a;
}

.stat-item.offline {
  color: #f56c6c;
}

/* 主机组节点样式 */
.group-node .node-label {
  color: #e6a23c;
  font-weight: 500;
}

.group-stats {
  margin-left: auto;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  background: rgba(164, 244, 186, 0.1);
  padding: 4px 8px;
  border-radius: 4px;
}

/* 主机节点样式 */
.host-node-content {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 15px;
  margin-left: auto;
}

.host-status {
  display: flex;
  align-items: center;
  gap: 6px;
}

.status-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border-radius: 50%;
}

.status-indicator.available {
  background: rgba(103, 194, 58, 0.2);
  color: #67c23a;
}

.status-indicator.unavailable {
  background: rgba(245, 108, 108, 0.2);
  color: #f56c6c;
}

.status-text {
  font-size: 12px;
  color: #ffffff;
}

.host-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 150px;
}

.ip-address {
  font-size: 12px;
  color: #a4f4ba;
}

.monitoring-status {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.6);
}

.host-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  width: 28px;
  height: 28px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  transition: all 0.3s ease;
}

/* 远程连接按钮 - 绿色 */
.connect-btn {
  background: rgba(34, 197, 94, 0.2) !important;
  border: 1px solid rgba(34, 197, 94, 0.4) !important;
  color: #22c55e !important;
}

.connect-btn:hover {
  background: rgba(34, 197, 94, 0.3) !important;
  border-color: rgba(34, 197, 94, 0.6) !important;
  box-shadow: 0 4px 16px rgba(34, 197, 94, 0.3) !important;
}

/* 查看详情按钮 - 青色 */
.monitor-btn {
  background: rgba(6, 182, 212, 0.2) !important;
  border: 1px solid rgba(6, 182, 212, 0.4) !important;
  color: #06b6d4 !important;
}

.monitor-btn:hover {
  background: rgba(6, 182, 212, 0.3) !important;
  border-color: rgba(6, 182, 212, 0.6) !important;
  box-shadow: 0 4px 16px rgba(6, 182, 212, 0.3) !important;
}

/* 配置按钮 - 紫色 */
.config-btn {
  background: rgba(138, 43, 226, 0.2) !important;
  border: 1px solid rgba(138, 43, 226, 0.4) !important;
  color: #8a2be2 !important;
}

.config-btn:hover {
  background: rgba(138, 43, 226, 0.3) !important;
  border-color: rgba(138, 43, 226, 0.6) !important;
  box-shadow: 0 4px 16px rgba(138, 43, 226, 0.3) !important;
}

.hosts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.host-card {
  padding: 20px;
  border-left: 4px solid rgba(164, 244, 186, 0.5);
}

.host-card.status-online {
  border-left-color: #22c55e;
}

.host-card.status-offline {
  border-left-color: #ef4444;
}

.host-card.status-unknown {
  border-left-color: #f59e0b;
}

.host-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.host-info h4 {
  color: rgba(255, 255, 255, 0.9);
  margin: 0 0 4px 0;
  font-size: 1.1rem;
}

.host-ip {
  color: rgba(255, 255, 255, 0.6);
  font-size: 0.9rem;
}

.host-status {
  display: flex;
  align-items: center;
  gap: 6px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 0.9rem;
}

.host-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  margin-bottom: 16px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-item .label {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.8rem;
}

.detail-item .value {
  color: rgba(255, 255, 255, 0.9);
  font-size: 0.8rem;
  font-weight: 500;
}

.alert-count.has-alerts {
  color: #ef4444;
  font-weight: bold;
}

.host-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.action-btn {
  background: rgba(164, 244, 186, 0.15);
  border: 1px solid rgba(164, 244, 186, 0.3);
  color: rgba(255, 255, 255, 0.9);
  padding: 6px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.8rem;
}

.action-btn:hover {
  background: rgba(164, 244, 186, 0.25);
  border-color: rgba(164, 244, 186, 0.5);
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: rgba(255, 255, 255, 0.6);
}

.empty-state i {
  font-size: 4rem;
  margin-bottom: 16px;
  color: rgba(164, 244, 186, 0.3);
}

.empty-state h3 {
  margin: 0 0 8px 0;
  color: rgba(255, 255, 255, 0.8);
}

.realtime-section {
  padding: 24px;
}

.section-title {
  color: #00eaff;
  font-size: 1.3rem;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 按钮样式 */
.glass-button {
  background: rgba(164, 244, 186, 0.15) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 8px !important;
  padding: 8px 16px !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;

  &:hover {
    background: rgba(164, 244, 186, 0.25) !important;
    border-color: rgba(164, 244, 186, 0.5) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 16px rgba(164, 244, 186, 0.2) !important;
  }

  i {
    margin-right: 6px !important;
    color: #00eaff !important;
  }
}

/* 刷新按钮 - 紫色 */
.refresh-button {
  background: rgba(138, 43, 226, 0.2) !important;
  border-color: rgba(138, 43, 226, 0.4) !important;

  &:hover {
    background: rgba(138, 43, 226, 0.3) !important;
    border-color: rgba(138, 43, 226, 0.6) !important;
    box-shadow: 0 4px 16px rgba(138, 43, 226, 0.3) !important;
  }

  i {
    color: #8a2be2 !important;
  }
}

/* 同步按钮 - 蓝色 */
.sync-button {
  background: rgba(59, 130, 246, 0.2) !important;
  border-color: rgba(59, 130, 246, 0.4) !important;

  &:hover {
    background: rgba(59, 130, 246, 0.3) !important;
    border-color: rgba(59, 130, 246, 0.6) !important;
    box-shadow: 0 4px 16px rgba(59, 130, 246, 0.3) !important;
  }

  i {
    color: #3b82f6 !important;
  }
}

/* 清理按钮 - 橙色 */
.cleanup-button {
  background: rgba(249, 115, 22, 0.2) !important;
  border-color: rgba(249, 115, 22, 0.4) !important;

  &:hover {
    background: rgba(249, 115, 22, 0.3) !important;
    border-color: rgba(249, 115, 22, 0.6) !important;
    box-shadow: 0 4px 16px rgba(249, 115, 22, 0.3) !important;
  }

  i {
    color: #f97316 !important;
  }
}

/* 添加按钮 - 绿色 */
.add-button {
  background: rgba(34, 197, 94, 0.2) !important;
  border-color: rgba(34, 197, 94, 0.4) !important;

  &:hover {
    background: rgba(34, 197, 94, 0.3) !important;
    border-color: rgba(34, 197, 94, 0.6) !important;
    box-shadow: 0 4px 16px rgba(34, 197, 94, 0.3) !important;
  }

  i {
    color: #22c55e !important;
  }
}

/* 保存按钮 - 绿色 */
.save-button {
  background: rgba(34, 197, 94, 0.2) !important;
  border-color: rgba(34, 197, 94, 0.4) !important;

  &:hover {
    background: rgba(34, 197, 94, 0.3) !important;
    border-color: rgba(34, 197, 94, 0.6) !important;
    box-shadow: 0 4px 16px rgba(34, 197, 94, 0.3) !important;
  }

  i {
    color: #22c55e !important;
  }
}

.text-success {
  color: #22c55e;
}

.text-danger {
  color: #ef4444;
}

.text-warning {
  color: #f59e0b;
}

/* 调试按钮样式 - 橙色 */
.debug-button {
  background: rgba(255, 165, 0, 0.2) !important;
  border-color: rgba(255, 165, 0, 0.4) !important;

  &:hover {
    background: rgba(255, 165, 0, 0.3) !important;
    border-color: rgba(255, 165, 0, 0.6) !important;
    box-shadow: 0 4px 16px rgba(255, 165, 0, 0.3) !important;
  }

  i {
    color: #ffa500 !important;
  }
}

/* 操作按钮样式 */
.action-glass-button {
  background: rgba(164, 244, 186, 0.1) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 6px !important;
  padding: 6px 12px !important;
  font-size: 12px !important;
  font-weight: 500 !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;

  &:hover {
    background: rgba(164, 244, 186, 0.2) !important;
    border-color: rgba(164, 244, 186, 0.5) !important;
    color: #ffffff !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(164, 244, 186, 0.2) !important;
  }

  i {
    margin-right: 4px !important;
    color: #00eaff !important;
  }

  /* 危险操作按钮 - 红色 */
  &.danger {
    background: rgba(239, 68, 68, 0.2) !important;
    border-color: rgba(239, 68, 68, 0.4) !important;

    &:hover {
      background: rgba(239, 68, 68, 0.3) !important;
      border-color: rgba(239, 68, 68, 0.6) !important;
      box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3) !important;
    }

    i {
      color: #ef4444 !important;
    }
  }
}

/* 主机卡片样式 */

.environment-section {
  margin-bottom: 30px;
}

.ungrouped-section {
  margin-bottom: 30px;
  margin-top: 20px;
}

.ungrouped-environment {
  border-left: 4px solid #f39c12 !important;
}

.ungrouped-host {
  border-left: 4px solid #f39c12 !important;
}

.unlinked-notice {
  margin-top: 12px;
  padding: 8px 12px;
  background: rgba(243, 156, 18, 0.1);
  border: 1px solid rgba(243, 156, 18, 0.3);
  border-radius: 6px;
  color: #f39c12;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.environment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 15px 20px;
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.3);
  border-radius: 8px;
  backdrop-filter: blur(10px);
  cursor: pointer;
  transition: all 0.3s ease;
}

.environment-header:hover {
  background: rgba(164, 244, 186, 0.15);
  border-color: rgba(164, 244, 186, 0.4);
}

.environment-header .header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.environment-header .expand-icon {
  color: #a4f4ba;
  transition: transform 0.3s ease;
  font-size: 14px;
  min-width: 14px;
}

.environment-header .expand-icon.expanded {
  transform: rotate(90deg);

  h3 {
    color: #a4f4ba;
    margin: 0;
    font-size: 18px;
    font-weight: 600;

    i {
      margin-right: 8px;
      color: #00eaff;
    }
  }

  .env-stats {
    display: flex;
    gap: 15px;

    .stat {
      display: flex;
      align-items: center;
      gap: 5px;
      color: #ffffff;
      font-size: 14px;

      i {
        font-size: 12px;
      }

      &.online {
        color: #4ade80;
      }

      &.total {
        color: #a4f4ba;
      }
    }
  }
}

.host-group-section {
  margin-bottom: 25px;
}

.group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 10px 15px;
  background: rgba(164, 244, 186, 0.05);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.group-header:hover {
  background: rgba(164, 244, 186, 0.1);
  border-color: rgba(164, 244, 186, 0.3);
}

.group-header .header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.group-header .expand-icon {
  color: #a4f4ba;
  transition: transform 0.3s ease;
  font-size: 12px;
  min-width: 12px;
}

.group-header .expand-icon.expanded {
  transform: rotate(90deg);
}

.group-header h4 {
  color: #a4f4ba;
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.group-header h4 i {
  margin-right: 6px;
  color: #fbbf24;
}

.group-header .group-stats {
  display: flex;
  gap: 10px;
  font-size: 12px;
}

.group-header .group-stats .stat {
  padding: 2px 8px;
  border-radius: 12px;
  font-weight: 500;
}

.group-header .group-stats .stat.online {
  background: rgba(34, 197, 94, 0.2);
  color: #4ade80;
}

.group-header .group-stats .stat.offline {
  background: rgba(239, 68, 68, 0.2);
  color: #f87171;
}

.group-header .group-stats .stat.total {
  background: rgba(164, 244, 186, 0.2);
  color: #a4f4ba;
}

.host-cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.host-card {
  padding: 16px;
  border-radius: 8px;
  border: 1px solid rgba(164, 244, 186, 0.3);
  background: rgba(164, 244, 186, 0.05);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(164, 244, 186, 0.15);
    border-color: rgba(164, 244, 186, 0.5);
  }

  &.host-card-online {
    border-left: 4px solid #4ade80;
  }

  &.host-card-offline {
    border-left: 4px solid #f87171;
  }

  &.host-card-unknown {
    border-left: 4px solid #fbbf24;
  }
}

.host-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.host-info {
  .host-name {
    color: #ffffff;
    margin: 0 0 4px 0;
    font-size: 16px;
    font-weight: 600;
  }

  .host-ip {
    color: #a4f4ba;
    font-size: 14px;
    font-family: 'Courier New', monospace;
  }
}

.host-status {
  display: flex;
  align-items: center;
  gap: 6px;

  .status-icon {
    font-size: 14px;

    &.fa-check-circle {
      color: #4ade80;
    }

    &.fa-times-circle {
      color: #f87171;
    }

    &.fa-question-circle {
      color: #fbbf24;
    }
  }

  .status-text {
    font-size: 12px;
    font-weight: 500;
    color: #ffffff;
  }
}

.host-actions {
  display: flex;
  justify-content: center;
  gap: 8px;

  .action-btn {
    padding: 6px 10px;
    border: 1px solid rgba(164, 244, 186, 0.3);
    background: rgba(164, 244, 186, 0.1);
    color: #a4f4ba;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 12px;

    &:hover {
      background: rgba(164, 244, 186, 0.2);
      border-color: rgba(164, 244, 186, 0.5);
      transform: translateY(-1px);
    }

    &.connect-btn:hover {
      color: #00eaff;
      border-color: rgba(0, 234, 255, 0.5);
      background: rgba(0, 234, 255, 0.1);
    }

    &.monitor-btn:hover {
      color: #4ade80;
      border-color: rgba(74, 222, 128, 0.5);
      background: rgba(74, 222, 128, 0.1);
    }

    &.config-btn:hover {
      color: #fbbf24;
      border-color: rgba(251, 191, 36, 0.5);
      background: rgba(251, 191, 36, 0.1);
    }
  }
}

/* 实时监控数据样式 */
.auto-refresh-indicator {
  margin-left: 15px;
  font-size: 14px;
  color: #a4f4ba;

  i {
    margin-right: 5px;
    color: #00eaff;
  }
}

.monitoring-data-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.host-monitoring-card {
  padding: 20px;
  border-radius: 10px;
  border: 1px solid rgba(164, 244, 186, 0.3);
  background: rgba(164, 244, 186, 0.05);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 30px rgba(164, 244, 186, 0.2);
    border-color: rgba(164, 244, 186, 0.5);
  }

  &.host-card-online {
    border-left: 4px solid #4ade80;
  }

  &.host-card-offline {
    border-left: 4px solid #f87171;
  }

  &.host-card-unknown {
    border-left: 4px solid #fbbf24;
  }
}

.host-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(164, 244, 186, 0.2);
}

.host-basic-info {
  .host-name {
    color: #ffffff;
    margin: 0 0 5px 0;
    font-size: 18px;
    font-weight: 600;
  }

  .host-ip {
    color: #a4f4ba;
    font-size: 14px;
    font-family: 'Courier New', monospace;
  }
}

.host-status-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 5px;

  &.status-online {
    background: rgba(74, 222, 128, 0.2);
    color: #4ade80;
    border: 1px solid rgba(74, 222, 128, 0.3);
  }

  &.status-offline {
    background: rgba(239, 68, 68, 0.2);
    color: #f87171;
    border: 1px solid rgba(239, 68, 68, 0.3);
  }

  &.status-unknown {
    background: rgba(251, 191, 36, 0.2);
    color: #fbbf24;
    border: 1px solid rgba(251, 191, 36, 0.3);
  }
}

.monitoring-metrics {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 15px;
  margin-bottom: 15px;
}

.metric-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: rgba(164, 244, 186, 0.05);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 8px;
  transition: all 0.2s ease;

  &:hover {
    background: rgba(164, 244, 186, 0.1);
    border-color: rgba(164, 244, 186, 0.3);
  }
}

.metric-label {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #a4f4ba;
  font-size: 13px;
  font-weight: 500;

  i {
    color: #00eaff;
    width: 16px;
  }
}

.metric-value {
  font-weight: 600;
  font-size: 14px;
  font-family: 'Courier New', monospace;

  &.metric-normal {
    color: #4ade80;
  }

  &.metric-warning {
    color: #fbbf24;
  }

  &.metric-critical {
    color: #f87171;
  }

  &.metric-unavailable {
    color: #909399;
    font-style: italic;
    opacity: 0.7;
  }
}

.last-update {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #a4f4ba;
  font-size: 12px;
  opacity: 0.8;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid rgba(164, 244, 186, 0.1);

  i {
    color: #00eaff;
  }
}

.no-data-tip {
  text-align: center;
  padding: 40px;
  color: #a4f4ba;
  font-size: 16px;

  i {
    font-size: 24px;
    margin-bottom: 10px;
    display: block;
    color: #00eaff;
  }
}

/* 监控指标分类展示样式 */
.metrics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.metrics-stats {
  display: flex;
  align-items: center;
  gap: 15px;
}

.total-count {
  color: #a4f4ba;
  font-size: 14px;
  background: rgba(164, 244, 186, 0.1);
  padding: 4px 12px;
  border-radius: 12px;
  border: 1px solid rgba(164, 244, 186, 0.3);
}

.refresh-btn {
  padding: 6px 12px;
  font-size: 12px;
  background: rgba(59, 130, 246, 0.1);
  border: 1px solid rgba(59, 130, 246, 0.3);
  color: #3b82f6;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.refresh-btn:hover:not(:disabled) {
  background: rgba(59, 130, 246, 0.2);
  border-color: rgba(59, 130, 246, 0.5);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.metrics-categories {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.metric-category {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  overflow: hidden;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: rgba(255, 255, 255, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
}

.category-header:hover {
  background: rgba(255, 255, 255, 0.1);
}

.category-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.category-icon {
  color: #a4f4ba;
  font-size: 16px;
}

.category-name {
  color: #ffffff;
  font-size: 16px;
  font-weight: 500;
}

.category-count {
  color: #94a3b8;
  font-size: 14px;
}

.category-header .expand-icon {
  color: #a4f4ba;
  transition: transform 0.3s ease;
  font-size: 14px;
}

.category-header .expand-icon.expanded {
  transform: rotate(90deg);
}

.category-content {
  padding: 20px;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 15px;
}

.metric-card {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 15px;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.metric-card:hover {
  background: rgba(255, 255, 255, 0.08);
  border-color: rgba(164, 244, 186, 0.3);
  transform: translateY(-2px);
}

.metric-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.metric-header i {
  color: #a4f4ba;
  font-size: 14px;
}

.metric-name {
  color: #ffffff;
  font-size: 14px;
  font-weight: 500;
  flex: 1;
}

.metrics-categories .metric-value {
  color: #ffffff;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 5px;
}

.metrics-categories .metric-value.metric-normal {
  color: #4ade80;
}

.metrics-categories .metric-value.metric-warning {
  color: #fbbf24;
}

.metrics-categories .metric-value.metric-critical {
  color: #f87171;
}

.metric-key {
  color: #94a3b8;
  font-size: 12px;
  font-family: 'Courier New', monospace;
  background: rgba(0, 0, 0, 0.2);
  padding: 2px 6px;
  border-radius: 4px;
  margin-top: 5px;
}

/* 透明玻璃样式 */
.glass-dialog {
  backdrop-filter: blur(10px);
}

.glass-dialog .el-dialog {
  background: rgba(255, 255, 255, 0.1) !important;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.glass-dialog .el-dialog__header {
  background: rgba(255, 255, 255, 0.05);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 16px 16px 0 0;
  padding: 20px 24px;
}

.glass-dialog .el-dialog__title {
  color: #ffffff;
  font-weight: 600;
}

.glass-dialog .el-dialog__body {
  background: transparent;
  padding: 24px;
}

.glass-input .el-input__wrapper {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.glass-input .el-input__inner {
  color: #ffffff;
  background: transparent !important;
}

.glass-input .el-input__inner::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.glass-button {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #ffffff;
  border-radius: 8px;
  padding: 8px 16px;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  cursor: pointer;
}

.glass-button:hover {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
}

.glass-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.glass-button-primary {
  background: rgba(64, 158, 255, 0.3);
  border-color: rgba(64, 158, 255, 0.5);
}

.glass-button-primary:hover {
  background: rgba(64, 158, 255, 0.4);
  border-color: rgba(64, 158, 255, 0.6);
}

.glass-button-secondary {
  background: rgba(245, 158, 11, 0.3);
  border-color: rgba(245, 158, 11, 0.5);
}

.glass-button-secondary:hover {
  background: rgba(245, 158, 11, 0.4);
  border-color: rgba(245, 158, 11, 0.6);
}

/* 监控指标弹窗样式优化 */
.metrics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;
}

.metrics-controls {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.search-container {
  display: flex;
  align-items: center;
}

.metrics-stats {
  display: flex;
  align-items: center;
  gap: 12px;
}

.total-count {
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

/* 监控项卡片样式优化 */
.metric-card {
  transition: all 0.3s ease;
}

.metric-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
}

.metric-name {
  display: block;
  word-break: break-word;
  line-height: 1.4;
}

.metric-value span {
  display: inline-block;
  max-width: 100%;
  word-break: break-all;
}

.metric-key code {
  display: inline-block;
  max-width: 100%;
  word-break: break-all;
  font-size: 11px;
}

/* 配置弹窗样式 */
.config-dialog .el-dialog {
  background: rgba(255, 255, 255, 0.1) !important;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.config-dialog .el-dialog__header {
  background: rgba(255, 255, 255, 0.05);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 16px 16px 0 0;
  padding: 20px 24px;
}

.config-dialog .el-dialog__title {
  color: #ffffff;
  font-weight: 600;
}

.config-dialog .el-dialog__body {
  background: transparent;
  padding: 24px;
}







.config-section {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
}

.config-section h3 {
  color: #ffffff;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.config-section h3 i {
  color: #00eaff;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.add-template-controls, .add-hostgroup-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.template-option, .hostgroup-option {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.template-option-name, .hostgroup-option-name {
  font-weight: 500;
  color: #303133;
}

.template-option-desc {
  font-size: 12px;
  color: #909399;
}

/* 模板选择器优化 */
.template-select .el-select__wrapper {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.template-select .el-input__inner {
  color: #ffffff;
  background: transparent !important;
}

.template-select .el-input__inner::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.hostgroup-select .el-select__wrapper {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.hostgroup-select .el-input__inner {
  color: #ffffff;
  background: transparent !important;
}

.hostgroup-select .el-input__inner::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

/* 下拉菜单样式优化 */
.template-dropdown {
  background: rgba(255, 255, 255, 0.95) !important;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  max-height: 300px;
  overflow-y: auto;
}

.hostgroup-dropdown {
  background: rgba(255, 255, 255, 0.95) !important;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  max-height: 250px;
  overflow-y: auto;
}

.template-option-item {
  padding: 8px 12px !important;
  margin: 2px 4px !important;
  border-radius: 6px !important;
  transition: all 0.2s ease !important;
}

.template-option-item:hover {
  background: rgba(64, 158, 255, 0.1) !important;
}

.template-option-item.is-selected {
  background: rgba(64, 158, 255, 0.2) !important;
  color: #409eff !important;
}

.hostgroup-option-item {
  padding: 8px 12px !important;
  margin: 2px 4px !important;
  border-radius: 6px !important;
  transition: all 0.2s ease !important;
}

.hostgroup-option-item:hover {
  background: rgba(64, 158, 255, 0.1) !important;
}

.hostgroup-option-item.is-selected {
  background: rgba(64, 158, 255, 0.2) !important;
  color: #409eff !important;
}

.template-option {
  display: flex;
  flex-direction: column;
  gap: 2px;
  width: 100%;
}

.template-option-name {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
  line-height: 1.2;
  word-break: break-word;
}

.template-option-desc {
  font-size: 11px;
  color: #909399;
  line-height: 1.2;
  word-break: break-word;
}

.hostgroup-option {
  display: flex;
  align-items: center;
  width: 100%;
}

.hostgroup-option-name {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
  line-height: 1.2;
  word-break: break-word;
}

/* 滚动条样式 */
.template-dropdown::-webkit-scrollbar,
.hostgroup-dropdown::-webkit-scrollbar {
  width: 6px;
}

.template-dropdown::-webkit-scrollbar-track,
.hostgroup-dropdown::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

.template-dropdown::-webkit-scrollbar-thumb,
.hostgroup-dropdown::-webkit-scrollbar-thumb {
  background: rgba(64, 158, 255, 0.3);
  border-radius: 3px;
}

.template-dropdown::-webkit-scrollbar-thumb:hover,
.hostgroup-dropdown::-webkit-scrollbar-thumb:hover {
  background: rgba(64, 158, 255, 0.5);
}

/* 搜索区域样式 */
.template-search-section, .hostgroup-search-section {
  margin-bottom: 20px;
}

.search-area {
  margin-bottom: 16px;
}

.search-input-group {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.search-input {
  flex: 1;
  max-width: 400px;
}

.search-input .el-input__wrapper {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.search-input .el-input__inner {
  color: #ffffff;
  background: transparent !important;
}

.search-input .el-input__inner::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.search-stats {
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
  background: rgba(64, 158, 255, 0.2);
  padding: 4px 8px;
  border-radius: 4px;
  white-space: nowrap;
}

/* 分类标签样式 */
.template-categories, .hostgroup-categories {
  margin-top: 16px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.category-title {
  color: rgba(255, 255, 255, 0.9);
  font-size: 13px;
  margin-bottom: 8px;
  font-weight: 500;
}

.category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.category-tag {
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 12px;
  border-radius: 6px;
}

.category-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

/* 搜索高亮样式 */
.search-highlight {
  background: rgba(255, 235, 59, 0.8);
  color: #333;
  padding: 1px 2px;
  border-radius: 2px;
  font-weight: 600;
}

/* 添加控件样式优化 */
.add-template-controls, .add-hostgroup-controls {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 12px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}



/* 响应式设计 */
@media (max-width: 768px) {
  .search-input-group {
    flex-direction: column;
    align-items: stretch;
  }

  .add-template-controls, .add-hostgroup-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .add-template-controls .template-select,
  .add-hostgroup-controls .hostgroup-select {
    width: 100% !important;
    margin-right: 0 !important;
    margin-bottom: 12px;
  }

  .category-tags {
    justify-content: center;
  }
}

.config-form .el-form-item__label {
  color: rgba(255, 255, 255, 0.9);
}

.templates-list, .hostgroups-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 300px;
  overflow-y: auto;
}

.template-item, .hostgroup-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.template-item:hover, .hostgroup-item:hover {
  background: rgba(255, 255, 255, 0.1);
  border-color: rgba(164, 244, 186, 0.3);
}

.template-info, .hostgroup-info {
  flex: 1;
}

.template-name, .hostgroup-name {
  color: #ffffff;
  font-weight: 500;
  margin-bottom: 4px;
}

.template-desc {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
}

.template-actions, .hostgroup-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: rgba(255, 255, 255, 0.6);
}

.empty-state i {
  font-size: 48px;
  color: rgba(255, 255, 255, 0.3);
  margin-bottom: 16px;
  display: block;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}

/* Zabbix服务器选择器样式 */
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.control-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.zabbix-selector {
  display: flex;
  align-items: center;
  gap: 12px;
}

.selector-label {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
  white-space: nowrap;
}

.selector-label i {
  color: #409eff;
}

.glass-select .el-select__wrapper {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.glass-select .el-select__placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.glass-select .el-input__inner {
  color: #ffffff;
  background: transparent !important;
}

.server-option {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.server-name {
  font-weight: 500;
  color: #303133;
}

.server-url {
  font-size: 12px;
  color: #909399;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .header-content {
    flex-direction: column;
    align-items: stretch;
  }

  .control-section {
    justify-content: center;
  }

  .action-section {
    justify-content: center;
  }
}

/* 简化的透明样式 - 避免死循环 */
.config-dialog {
  background: rgba(255, 255, 255, 0.1) !important;
  backdrop-filter: blur(10px) !important;
}

/* 接口配置样式 */
.interfaces-list {
  margin-top: 16px;
}

.interface-item {
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 8px;
}

.interface-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.interface-type {
  display: flex;
  gap: 8px;
  align-items: center;
}

.interface-actions {
  display: flex;
  gap: 8px;
}

.interface-details {
  margin-top: 12px;
}

.interface-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item .label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  font-weight: 500;
}

.info-item .value {
  font-size: 14px;
  color: #ffffff;
}

/* 宏变量样式 */
.macros-list {
  margin-top: 16px;
}

.macro-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  margin-bottom: 12px;
  border-radius: 8px;
}

.macro-content {
  flex: 1;
}

.macro-name {
  font-size: 14px;
  font-weight: 600;
  color: #00eaff;
  margin-bottom: 4px;
}

.macro-value {
  font-size: 13px;
  color: #ffffff;
  margin-bottom: 4px;
}

.macro-desc {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

.macro-actions {
  display: flex;
  gap: 8px;
}

/* 监控项样式 */
.items-search {
  display: flex;
  align-items: center;
}

.items-list {
  margin-top: 16px;
  max-height: 500px;
  overflow-y: auto;
}

.items-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

.glass-pagination {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 8px;
  padding: 8px;
}

.items-summary {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.summary-label {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
}

.summary-count {
  color: #00eaff;
  font-weight: 600;
  font-size: 14px;
}

.items-category {
  margin-bottom: 24px;
}

.category-title {
  color: #00eaff;
  margin-bottom: 12px;
  padding: 8px 12px;
  background: rgba(0, 234, 255, 0.1);
  border-radius: 6px;
  border-left: 3px solid #00eaff;
  font-size: 16px;
  font-weight: 600;
}

.custom-item {
  border-left: 3px solid #67c23a;
}

.template-item {
  border-left: 3px solid #909399;
  opacity: 0.9;
}

.item-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 8px;
  border-radius: 6px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 14px;
  font-weight: 500;
  color: #ffffff;
  margin-bottom: 4px;
}

.item-key {
  font-size: 12px;
  color: #00eaff;
  margin-bottom: 2px;
}

.item-type {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.6);
}

.item-status {
  margin: 0 16px;
}

.item-actions {
  display: flex;
  gap: 8px;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: rgba(255, 255, 255, 0.6);
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state p {
  font-size: 14px;
  margin: 0;
}

/* 操作按钮样式 */
.action-glass-button {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  color: #ffffff !important;
  backdrop-filter: blur(10px) !important;
  transition: all 0.3s ease !important;
}

.action-glass-button:hover {
  background: rgba(255, 255, 255, 0.2) !important;
  border-color: rgba(255, 255, 255, 0.4) !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;
}

.action-glass-button.primary {
  border-color: rgba(64, 158, 255, 0.4) !important;
  color: #409eff !important;
}

.action-glass-button.primary:hover {
  border-color: rgba(64, 158, 255, 0.6) !important;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3) !important;
}

.action-glass-button.danger {
  border-color: rgba(245, 108, 108, 0.4) !important;
  color: #f56c6c !important;
}

.action-glass-button.danger:hover {
  border-color: rgba(245, 108, 108, 0.6) !important;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3) !important;
}

.action-glass-button.info {
  border-color: rgba(144, 147, 153, 0.4) !important;
  color: #909399 !important;
}

.action-glass-button.info:hover {
  border-color: rgba(144, 147, 153, 0.6) !important;
  box-shadow: 0 4px 12px rgba(144, 147, 153, 0.3) !important;
}

/* 骨架屏样式 */
.skeleton-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.skeleton-card {
  padding: 20px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

.skeleton-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.skeleton-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(90deg, rgba(255, 255, 255, 0.1) 25%, rgba(255, 255, 255, 0.2) 50%, rgba(255, 255, 255, 0.1) 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s infinite;
  margin-right: 12px;
}

.skeleton-text-group {
  flex: 1;
}

.skeleton-text {
  height: 12px;
  background: linear-gradient(90deg, rgba(255, 255, 255, 0.1) 25%, rgba(255, 255, 255, 0.2) 50%, rgba(255, 255, 255, 0.1) 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s infinite;
  border-radius: 6px;
  margin-bottom: 8px;
}

.skeleton-title {
  width: 60%;
  height: 16px;
}

.skeleton-subtitle {
  width: 40%;
  height: 12px;
}

.skeleton-short {
  width: 30%;
}

.skeleton-content .skeleton-text:nth-child(1) {
  width: 80%;
}

.skeleton-content .skeleton-text:nth-child(2) {
  width: 65%;
}

@keyframes skeleton-loading {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

/* 新增按钮样式 */
.action-section {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.sync-dropdown, .display-dropdown {
  display: inline-block;
}

.sync-button {
  background: rgba(138, 43, 226, 0.2) !important;
  border: 1px solid rgba(138, 43, 226, 0.4) !important;
  color: #ba68c8 !important;
}

.sync-button:hover {
  background: rgba(138, 43, 226, 0.3) !important;
  border-color: rgba(138, 43, 226, 0.6) !important;
}

.display-button {
  background: rgba(0, 150, 136, 0.2) !important;
  border: 1px solid rgba(0, 150, 136, 0.4) !important;
  color: #4db6ac !important;
}

.display-button:hover {
  background: rgba(0, 150, 136, 0.3) !important;
  border-color: rgba(0, 150, 136, 0.6) !important;
}

.management-button {
  background: rgba(255, 152, 0, 0.2) !important;
  border: 1px solid rgba(255, 152, 0, 0.4) !important;
  color: #ffb74d !important;
}

.management-button:hover {
  background: rgba(255, 152, 0, 0.3) !important;
  border-color: rgba(255, 152, 0, 0.6) !important;
}

.refresh-button {
  background: rgba(76, 175, 80, 0.2) !important;
  border: 1px solid rgba(76, 175, 80, 0.4) !important;
  color: #81c784 !important;
}

.refresh-button:hover {
  background: rgba(76, 175, 80, 0.3) !important;
  border-color: rgba(76, 175, 80, 0.6) !important;
}

/* 下拉菜单样式 */
.glass-dropdown {
  background: rgba(0, 0, 0, 0.8) !important;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  border-radius: 8px;
}

.glass-dropdown .el-dropdown-menu__item {
  color: rgba(255, 255, 255, 0.9) !important;
  background: transparent !important;
  transition: all 0.3s ease;
}

.glass-dropdown .el-dropdown-menu__item:hover {
  background: rgba(255, 255, 255, 0.1) !important;
  color: #fff !important;
}

.glass-dropdown .el-dropdown-menu__item i {
  margin-right: 8px;
  width: 16px;
}

/* 主机管理对话框样式 */
.host-management-content {
  padding: 20px;
}

.management-header h4 {
  color: #fff;
  margin: 0 0 8px 0;
  font-size: 18px;
}

.management-header .description {
  color: rgba(255, 255, 255, 0.7);
  margin: 0 0 20px 0;
  font-size: 14px;
}

.management-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-label {
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
  margin-bottom: 4px;
}

.stat-value {
  color: #fff;
  font-size: 18px;
  font-weight: bold;
}

.stat-value.success {
  color: #4caf50;
}

.stat-value.warning {
  color: #ff9800;
}

.quick-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.unlinked-hosts-section h5 {
  color: #fff;
  margin: 0 0 15px 0;
  font-size: 16px;
}

.host-list {
  max-height: 300px;
  overflow-y: auto;
}

.host-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.host-info {
  display: flex;
  flex-direction: column;
}

.hostname {
  color: #fff;
  font-weight: 500;
  margin-bottom: 4px;
}

.ip {
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
}

.no-unlinked {
  text-align: center;
  padding: 40px;
  color: rgba(255, 255, 255, 0.7);
}

.no-unlinked i {
  font-size: 48px;
  color: #4caf50;
  margin-bottom: 16px;
}

/* 自动刷新设置对话框样式 */
.auto-refresh-content {
  padding: 20px;
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.setting-label {
  color: #fff;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 间隔设置特殊样式 */
.interval-setting {
  justify-content: flex-start;
  gap: 20px;
}

.interval-setting .setting-label {
  margin-right: 0;
  flex-shrink: 0;
}


</style>
